<分区>
我想将字符串 'one two three'
转换为 one_two_three
。
我试过 "_".join('one two three')
,但这给了我 o_n_e_ _t_w_o_ _t_h_r_e_e_
...
如何仅在字符串中单词之间的空格处插入 "_"
?
<分区>
我想将字符串 'one two three'
转换为 one_two_three
。
我试过 "_".join('one two three')
,但这给了我 o_n_e_ _t_w_o_ _t_h_r_e_e_
...
如何仅在字符串中单词之间的空格处插入 "_"
?
最佳答案
可以使用字符串的替换方法:
'one two three'.replace(' ', '_')
# 'one_two_three'
str.join
方法将一个可迭代对象作为参数并将可迭代对象中的字符串连接起来,字符串本身就是一个可迭代对象,因此您将通过 _
分隔每个字符你指定,如果你直接调用 _.join(some string)
。
关于python - 如何从字符串中加入()单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476490/