我正在编写一个脚本,它将以用户输入的字符串为输入,并垂直打印它,像这样:
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
有什么建议吗?(另外,我希望只使用一次打印命令。)
izip_longest
。 - wim