2017-03-08 35 views

回答

1

您可以在模式中使用反向引用匹配重複的字符,然後與匹配字符的兩個實例代替它,在這裏(.)\1+將匹配包含相同字符兩次或更多次的模式,代之以只有兩種情況下,通過\1\1

import re 
re.sub(r"(.)\1+", r"\1\1", s) 
# "heyy how are youu, it's so cool here, cool." 
+1

很好用!謝謝。 – Ash

0

創建一個新的文本,只如果沒有連續3次

text = "heyy how are youuuuu, it's so cool here, cooool." 

new_text = '' 
for i in range(len(text)): 
    try: 
     if text[i]==text[i+1]==text[i+2]: 
      pass 
     else: 
      new_text+=text[i] 
    except: 
     new_text+=text[i] 

print new_text 
>>>heyy how are youu, it's so cool here, cool. 
添加到它

eta:嗯只是注意到你要求「正則表達式」,所以批准答案更好;雖然這個作品

相關問題