小编典典

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

all

有没有更简单的方法将列表中的字符串项连接成单个字符串?我可以使用该str.join()功能吗?

例如,这是输入['this','is','a','sentence'],这是所需的输出this-is-a-sentence

sentence = ['this','is','a','sentence']
sent_str = ""
for i in sentence:
    sent_str += str(i) + "-"
sent_str = sent_str[:-1]
print sent_str

阅读 106

收藏
2022-02-28

共1个答案

小编典典

使用str.join

>>> sentence = ['this', 'is', 'a', 'sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
>>> ' '.join(sentence)
'this is a sentence'
2022-02-28