【问题标题】:How to join() words from a string? [duplicate]如何从字符串中加入()单词? [复制]
【发布时间】: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_...

如何将"_" 仅插入字符串中单词之间的空格?

【问题讨论】:

    标签: python string


    【解决方案1】:

    你可以使用字符串的替换方法:

    'one two three'.replace(' ', '_')
    # 'one_two_three'
    

    str.join 方法将一个可迭代对象作为参数并连接可迭代对象中的字符串,字符串本身就是一个可迭代对象,因此如果您直接调用_.join(some string),您将使用您指定的_ 分隔每个字符。

    【讨论】:

      【解决方案2】:

      你也可以拆分/加入:

      '_'.join('one two three'.split())
      

      【讨论】:

        【解决方案3】:

        如果你只想使用 join ,那么你可以这样做test="test string".split() "_".join(test) 这将为您提供“test_string”的输出。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-08-08
          • 1970-01-01
          • 2021-10-12
          • 2021-08-13
          • 2016-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多