【问题标题】:How to remove characters that repeat more than twice in a row/together in a string using python?如何使用python删除在字符串中连续/一起重复两次以上的字符?
【发布时间】:2022-07-22 01:36:21
【问题描述】:

我们如何将haaaaaaapppppyyyyyy 之类的字符串缩减为haappyy 这样字符串中的一个字符连续最多允许重复两次吗?

包括任何字符(也包括特殊字符) 将--------------------- 转换为--

【问题讨论】:

    标签: python regex replace data-cleaning data-preprocessing


    【解决方案1】:

    我们可以使用正则表达式替换:

    inp = "haaaaaaapppppyyyyyy"
    output = re.sub(r'(\w)\1{2,}', r'\1\1', inp)
    print(output)  # haappyy
    

    上述逻辑匹配任何一个其后跟两次或多次的字符。然后它只替换为两个字符。

    【讨论】:

    • 我们怎样才能使特殊字符也能工作?将--------------------- 转换为--
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-03
    • 2019-09-02
    • 1970-01-01
    • 2015-01-26
    • 2018-10-21
    • 1970-01-01
    相关资源
    最近更新 更多