本文介绍了将列表中的项目连接到字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有更简单的方法将列表中的字符串项连接为单个字符串?我可以使用str.join()
函数吗?
Is there a simpler way to concatenate string items in a list into a single string? Can I use the str.join()
function?
例如这是输入['this','is','a','sentence']
,这是所需的输出this-is-a-sentence
E.g. this is the input ['this','is','a','sentence']
and this is the desired output 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
推荐答案
使用 join
:
>>> sentence = ['this','is','a','sentence']
>>> '-'.join(sentence)
'this-is-a-sentence'
这篇关于将列表中的项目连接到字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!