Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
506 views
in Technique[技术] by (71.8m points)

vertical print string in python 3

I'm trying to write a code to have a phrase print vertically and it needs to be printed a certain away. I'm having the user input a string but I need the output to look a certain way with spaces. I have some of the code written already:

def main():

    #have user input phrase
    phrase = input("Enter a phrase:  ")
    print() # turnin
    print() #blank line
    print("Original phrase:",phrase)
    print() # blank line

    word_l = phrase.split()
    word_a = len(word_l)

    max_len = 6
    for i in range(word_a):
        length = len(word_l[i])
        if length < max_len:
             print(len(word_l[i]) * " ",end="")

I need to have 2 loops inside each other for the next part but I don't believe the above loop and if statement are correct. So the say the user inputs the phrase: Phil likes to code. I need the output to look like:

P    l     t  c
h    i     o  o
i    i        d
l    k        e
     e
     s

The spaces in between the words are the spaces as if the letters were there including one space. I can't use any imports and the only function I can use is split. I need to have a for loop with an if statement there and then I need another for loop with a for loop inside of that. Would really appreciate any help.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

An easier method is to use zip_longest from itertools

import itertools

txt = "some random text"

l = txt.split(' ')

for i in itertools.zip_longest(*l, fillvalue=" "):
    if any(j != " " for j in i):
        print(" ".join(i))

The previous code will give you

s r t
o a e
m n x
e d t
  o  
  m  

To add additional spaces between the words increase spaces in print(" ".join(i))

You can change txt to input of course


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...