如何将列表中的项目连接(联接)到单个字符串?

2022-09-05 01:10:45

如何将字符串列表连接成单个字符串?例如,给定一个列表,我如何得到一个字符串,如?['this', 'is', 'a', 'sentence']'this-is-a-sentence'


答案 1

使用 str.join

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

答案 2

将python列表转换为字符串的更通用的方法是:

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