【发布时间】:2017-01-05 02:34:58
【问题描述】:
我想将字符串'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),您将使用您指定的_ 分隔每个字符。
【讨论】:
你也可以拆分/加入:
'_'.join('one two three'.split())
【讨论】:
如果你只想使用 join ,那么你可以这样做test="test string".split()
"_".join(test)
这将为您提供“test_string”的输出。
【讨论】: