5

我正在编写一个脚本,它将作为用户输入的字符串,并垂直打印,如下所示:

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

有什么建议吗?(另外,我想让print命令只使用一次。)

4

3 回答 3

10

使用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      
于 2013-10-27T19:07:58.310 回答
0

非常感谢你的帮忙!这绝对有效!

发布此消息后不久,我最终与我的一位朋友交谈,并将 for 循环修改为以下内容:

newline = ""

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

效果也很好。

于 2013-10-27T19:21:19.253 回答
-2
a = input()
for x in range (0,len(a)):
    print(a[x])
于 2020-12-09T11:29:34.793 回答