垂直打印字符串 - Python3.2

6

我正在编写一个脚本,它将以用户输入的字符串为输入,并垂直打印它,像这样:

input = "John walked to the store"

output = J w t t s
         o a o h t
         h l   e o
         n k     r
           e     e
           d

我已经写了大部分的代码,如下所示:
import sys

def verticalPrint(astring):
    wordList = astring.split(" ")
    wordAmount = len(wordList)

    maxLen = 0
    for i in range (wordAmount):
        length = len(wordList[i])
        if length >= maxLen:
            maxLen = length

    ### makes all words the same length to avoid range errors ###
    for i in range (wordAmount):
        if len(wordList[i]) < maxLen:
            wordList[i] = wordList[i] + (" ")*(maxLen-len(wordList[i]))

    for i in range (wordAmount):
        for j in range (maxLen):
            print(wordList[i][j])

def main():
    astring = input("Enter a string:" + '\n')

    verticalPrint(astring)

main()

我在弄清楚如何正确输出时遇到了问题。我知道这是一个for循环的问题。它的输出为:

input = "John walked"

output = J
         o
         h
         n

         w
         a
         l
         k
         e
         d

有什么建议吗?(另外,我希望只使用一次打印命令。)

3个回答

12

使用 itertools.zip_longest

>>> from itertools import zip_longest
>>> text = "John walked to the store"
for x in zip_longest(*text.split(), fillvalue=' '):
    print (' '.join(x))
...     
J w t t s
o a o h t
h l   e o
n k     r
  e     e
  d      

非常好。或者在Python 2.x中使用izip_longest - wim

0

非常感谢您的帮助!那绝对有效!

我在发帖后不久就和我的一位朋友交谈了,然后我修改了for循环如下:

newline = ""

    for i in range (maxLen):
        for j in range (wordAmount):
            newline = newline + wordList[j][i]
        print (newline)
        newline = ""

这也非常完美地运作了。


-2
a = input()
for x in range (0,len(a)):
    print(a[x])

这并没有解决原帖作者的问题,它只会将所有字母都打印在新行中,你的缩进有问题,而且你的代码没有任何解释,尝试编辑你的答案或考虑将其删除,因为它是不正确的。 - Ruli

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接