2013-10-27 54 views
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 

有什麼建議嗎? (另外,我想有隻使用過一次的打印命令

回答

8

使用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  
+0

非常好。或者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 = "" 

其工作精美的爲好。