如何将一个字符串列表连接成一个字符串?
例如,给定['this', 'is', 'a', 'sentence'],我如何得到"this-is-a-sentence"?
要在单独的变量中处理几个字符串,请参见如何在Python中将一个字符串附加到另一个字符串。
对于相反的过程-从字符串创建列表-请参阅如何将字符串分割为字符列表?或如何将字符串分割成单词列表?是合适的。
如何将一个字符串列表连接成一个字符串?
例如,给定['this', 'is', 'a', 'sentence'],我如何得到"this-is-a-sentence"?
要在单独的变量中处理几个字符串,请参见如何在Python中将一个字符串附加到另一个字符串。
对于相反的过程-从字符串创建列表-请参阅如何将字符串分割为字符列表?或如何将字符串分割成单词列表?是合适的。
当前回答
使用str.join:
>>> words = ['this', 'is', 'a', 'sentence']
>>> '-'.join(words)
'this-is-a-sentence'
>>> ' '.join(words)
'this is a sentence'
其他回答
我们还可以使用Python的reduce函数:
from functools import reduce
sentence = ['this','is','a','sentence']
out_str = str(reduce(lambda x,y: x+"-"+y, sentence))
print(out_str)
一种更通用的方法(也包括数字列表)将列表转换为字符串:
>>> 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
如果没有.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变量。
如果你想在最终结果中生成一个由逗号分隔的字符串,你可以使用这样的方法:
sentence = ['this','is','a','sentence']
sentences_strings = "'" + "','".join(sentence) + "'"
print (sentences_strings) # you will get "'this','is','a','sentence'"
如果你有一个混合内容列表,想要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']