如果前两个字母在python中重复,则替换

use*_*562 1 python regex

如果单词中的前两个字母用相同的字母重复,如何替换?

例如,

 string = 'hhappy'
Run Code Online (Sandbox Code Playgroud)

我想得到

happy
Run Code Online (Sandbox Code Playgroud)

我试过了

re.sub(r'(.)\1+', r'\1', string)
Run Code Online (Sandbox Code Playgroud)

但是,这给了

hapy
Run Code Online (Sandbox Code Playgroud)

谢谢!

And*_*ndy 5

您需要添加一个插入符号(^)以仅匹配该行的开头.

re.sub(r'^(.)\1+', r'\1', string)
Run Code Online (Sandbox Code Playgroud)

例:

import re
string = 'hhappy'
print re.sub(r'^(.)\1+', r'\1', string)
Run Code Online (Sandbox Code Playgroud)

打印:

happy
Run Code Online (Sandbox Code Playgroud)

以上仅适用于该行的开头.如果您需要为每个单词执行此操作,则需要执行以下操作:

re.sub(r'\b(\w)\1+', r'\1', string)
Run Code Online (Sandbox Code Playgroud)