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

Categories

0 votes
296 views
in Technique[技术] by (71.8m points)

python - 将列表中的项目连接到字符串(Concatenate item in list to strings)

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

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

1 Answer

0 votes
by (71.8m points)

Use join :

(使用join :)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...