vertical print string in python 3

六月ゝ 毕业季﹏ 提交于 2021-01-01 06:12:30

问题


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.


回答1:


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




回答2:


How about this?

phrase = "Phil likes to code"

words = phrase.split()

maxlen = max([len(w) for w in words])


#now, you dont need max len , you can do a while True
#and break if all the words[ix] hit an IndexError

print "012346789"
for ix in range(maxlen):
    line = ""
    for w in words:

        try:
            line += w[ix]
        except IndexError:
            line += " "
        line += " "
    print line

and the output is:

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


来源:https://stackoverflow.com/questions/32872306/vertical-print-string-in-python-3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!