计算打印语句中的表达式


>>>line=['hello',' this',' is', 'a',' test']  
>>>print line
['hello', 'this', 'is', 'a', 'test']

但是我希望在打印行时,它应该是一个完整的字符串,而不是列表的元素。这是我尝试过的:

>>> print line[k] for k in len(line)
SyntaxError: invalid syntax

如何将此列表行打印为字符串?

有几种不同的方法可以在python中连接字符串。如果您有一个列表并希望连接其内容,则首选方法通常是 .join(list)

line=['hello',' this',' is', ' a',' test']
print ''.join(line)

有关更多方法,请参阅 http://www.pythonforbeginners.com/concatenation/string-concatenation-and-formatting-in-python

如果你想使用 for 循环(不推荐,但可能),你可以做类似的事情

line=['hello',' this',' is', ' a',' test']
concatenated_line = ''
for word in line:
    concatenated_line += word
print concatenated_line
line=['hello',' this',' is', 'a',' test'] 
str1 = ' '.join(line)
print str1
# hello this is a test

最新更新