Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is there a simpler way to concatenate string items in a list into a single string?

(有没有更简单的方法将列表中的字符串项连接为单个字符串?)

Can I use the str.join() function?

(我可以使用str.join()函数吗?)

Eg this is the input ['this','is','a','sentence'] and this is the desired output this-is-a-sentence

(例如,这是输入['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
  ask by alvas translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
302 views
Welcome To Ask or Share your Answers For Others

1 Answer

Use join :

(使用join :)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...