【问题标题】:Evaluate an expression in print statement [duplicate]评估打印语句中的表达式[重复]
【发布时间】:2016-11-11 23:03:38
【问题描述】:
>>>line=['hello',' this',' is', 'a',' test']  
>>>print line
['hello', 'this', 'is', 'a', 'test']

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

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

这个列表行如何打印为字符串?

【问题讨论】:

  • print ' '.join(line)

标签: python


【解决方案1】:

在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

【讨论】:

    【解决方案2】:
    line=['hello',' this',' is', 'a',' test'] 
    str1 = ' '.join(line)
    print str1
    # hello this is a test
    

    【讨论】:

    • 但我希望它与其他东西也打印在同一行
    • 虽然代码通常不言自明,但最好在代码中添加一些解释。这会在审核队列中弹出,因为只有代码的答案往往如此。
    猜你喜欢
    • 2011-07-22
    • 2014-12-08
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2014-06-12
    • 2011-01-27
    • 2010-10-22
    • 2015-06-26
    相关资源
    最近更新 更多