如何将一个字符串列表连接成一个字符串?

例如,给定['this', 'is', 'a', 'sentence'],我如何得到"this-is-a-sentence"?


要在单独的变量中处理几个字符串,请参见如何在Python中将一个字符串附加到另一个字符串。

对于相反的过程-从字符串创建列表-请参阅如何将字符串分割为字符列表?或如何将字符串分割成单词列表?是合适的。


当前回答

我们可以指定如何连接字符串。我们可以用' '代替'-':

sentence = ['this','is','a','sentence']
s=(" ".join(sentence))
print(s)

其他回答

使用str.join:

>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'

如果没有.join()方法,你可以使用这个方法:

my_list=["this","is","a","sentence"]

concenated_string=""
for string in range(len(my_list)):
    if string == len(my_list)-1:
        concenated_string+=my_list[string]
    else:
        concenated_string+=f'{my_list[string]}-'
print([concenated_string])
    >>> ['this-is-a-sentence']

因此,在这个例子中,基于range的for循环,当python到达列表的最后一个单词时,它不应该将"-"添加到你的concenated_string中。如果它不是你的字符串的最后一个词,总是附加"-"字符串到你的concenated_string变量。

来自未来的编辑:请不要使用下面的答案。这个函数在python3中被移除,python2已经死亡。即使你仍在使用Python 2,你也应该编写Python 3就绪代码,使不可避免的升级更容易。


虽然@Burhan Khalid的回答很好,但我认为这样更容易理解:

from str import join

sentence = ['this','is','a','sentence']

join(sentence, "-") 

join()的第二个参数是可选的,默认为" "。

一种更通用的方法(也包括数字列表)将列表转换为字符串:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
12345678910

如果你有一个混合内容列表,想要stringify它,这里有一种方法:

考虑一下这个列表:

>>> aa
[None, 10, 'hello']

将其转换为字符串:

>>> st = ', '.join(map(str, map(lambda x: f'"{x}"' if isinstance(x, str) else x, aa)))
>>> st = '[' + st + ']'
>>> st
'[None, 10, "hello"]'

如果需要,转换回列表:

>>> ast.literal_eval(st)
[None, 10, 'hello']