2013-01-20 60 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$