Python re.sub to replace 3 or more of same character with 1

后端 未结 3 827
耶瑟儿~
耶瑟儿~ 2021-01-06 15:15

I\'m trying to find characters that are repeated 3 times or more, for example I want to take the following strings:

(\'aaa\', \'buuuuut\',

相关标签:
3条回答
  • 2021-01-06 15:48
    >>> s = 'abbcccffffdd'
    >>> s = re.sub(r'(\w)\1(\1+)',r'\1',s)
    >>> s
    'abbcd'
    
    0 讨论(0)
  • 2021-01-06 15:52

    Look at this:

    >>> mystr = 'buuuuuttttt'
    >>> re.sub(r'(.)\1{2,}', r'\1', mystr)
    'but'
    >>> mystr = 'buttt'
    >>> re.sub(r'(.)\1{2,}', r'\1', mystr)
    'but'
    >>>
    
    0 讨论(0)
  • 2021-01-06 16:03

    Maybe try something like this:

    s = re.sub(r'(\w)\1\1+', r'\1', s)
    
    0 讨论(0)
提交回复
热议问题