【问题标题】:cant replace more than 1 underscore with a single underscore in the string(regex python)不能用字符串中的单个下划线替换超过 1 个下划线(正则表达式 python)
【发布时间】:2019-03-14 16:30:25
【问题描述】:
def strip_string(s):
    import re
    replaced_string = re.sub('[^\\w/]+', '_', s)
    return replaced_string
print(strip_string('h^&ell`.,  |o w/p]{+p__orld'))

【问题讨论】:

    标签: regex python-3.x replace


    【解决方案1】:

    如果您想使用regex 将字符串中的多个_ 替换为单个_,您可以这样做

    replaced_string = re.sub('[_]+', '_', s)

    完整代码,

    import re
    
    def strip_string(s):
    
        replaced_string = re.sub('[_]+', '_', s)
        return replaced_string
    print(strip_string('h^&ell`.,  |o w/p]{+p__orld'))
    print(strip_string('hello___world__'))
    
    # Output
    h^&ell`.,  |o w/p]{+p_orld
    hello_world_
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-25
      • 1970-01-01
      • 1970-01-01
      • 2020-05-11
      相关资源
      最近更新 更多