3
我正在寫一個腳本,將採取爲用戶inputed字符串,並垂直打印出來,像這樣:我已經寫了大部分的代碼,這是垂直打印字符串 - Python3.2
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
有什麼建議嗎? (另外,我想有隻使用過一次的打印命令)
非常好。或者Python 2.x上的'izip_longest' – wim