将列表中的单词分配给每个单词之间带有空格的字符串

时间:2015-04-07 03:36:19

标签: python string list loops

我想将列表中的单词转换为空字符串,但我也需要将单词用空格分隔。不要粘在一起。

例如:

def list_to_string(words):
    sentence = ""
    for word in words:
        sentence = sentence + word
return sentence

测试:

list_to_string(["moo", "lee", "raa", "soo"])
'mooleeraasoo'

但是我要找的是每两个单词之间的空格字符:

'moo lee raa soo'

2 个答案:

答案 0 :(得分:3)

您可以使用单行join而不使用循环。

' '.join(["moo", "lee", "raa", "soo"])
'moo lee raa soo'

答案 1 :(得分:1)

对于每次迭代,在单词中添加一个空格,最后在返回结果字符串时进行剥离。

def list_to_string(words):
    sentence = ""
    for word in words:
        sentence += word + " "
    return sentence.rstrip()     # before returning the string, this would strip all the trailing spaces.