2013-01-20 100 views
3

列表下面的程序的目的是單詞4個字符轉換從"This""T***",我已經完成了艱難的部分獲得該名單和len工作。把功能輸出在Python

的問題是程序輸出由行答案行了,我不知道是否有無論如何,我可以回到存儲輸出到一個列表,並把它打印出來作爲一個完整的句子?

謝謝。

#Define function to translate imported list information 
def translate(i): 
    if len(i) == 4: #Execute if the length of the text is 4 
     translate = i[0] + "***" #Return *** 
     return (translate) 
    else: 
     return (i) #Return original value 

#User input sentense for translation 
orgSent = input("Pleae enter a sentence:") 
orgSent = orgSent.split (" ") 

#Print lines 
for i in orgSent: 
    print(translate(i)) 

回答

3

在PY 2.x的,你可以添加一個,print

for i in orgSent: 
    print translate(i), 

如果你在PY 3.x中,然後請嘗試:

for i in orgSent: 
    print(translate(i),end=" ") 

end默認值是一個換行符(\n),這就是爲什麼每個字被印上了新的生產線。

+0

串行downvoter,FY。 –

3

使用列表理解和join方法:

translated = [translate(i) for i in orgSent] 
print(' '.join(translated)) 

列表理解基本函數的返回值存儲在一個列表中,你想要什麼。你可以做這樣的事情,比如:

print([i**2 for i in range(5)]) 
# [0, 1, 4, 9, 16] 

map功能也可能是有用的 - 它映射「到一個可迭代的每個元素的功能。在Python 2中,它返回一個列表。但是在Python 3(我假設你使用),它返回一個map對象,這也是可以傳遞到join功能的迭代。

translated = map(translate, orgSent) 

join方法加入與.前的字符串,括號內的迭代的每個元素。例如:

lis = ['Hello', 'World!'] 
print(' '.join(lis)) 
# Hello World! 

它不僅限於空間,你可以做一些瘋狂的是這樣的:

print('foo'.join(lis)) 
# HellofooWorld! 
1
sgeorge-mn:tmp sgeorge$ python s 
Pleae enter a sentence:"my name is suku john george" 
my n*** is s*** j*** george 

你只需要,打印。見下面的粘貼代碼部分的最後一行。

#Print lines 
for i in orgSent: 
    print (translate(i)), 

爲了您更多的瞭解:

sgeorge-mn:~ sgeorge$ cat tmp.py 
import sys 
print "print without ending comma" 
print "print without ending comma | ", 
sys.stdout.write("print using sys.stdout.write ") 

sgeorge-mn:~ sgeorge$ python tmp.py 
print without ending comma 
print without ending comma | print using sys.stdout.write sgeorge-mn:~ sgeorge$