Using a regular expression to replace upper case repeated letters in python with a single lowercase letter
Pass a function as the repl
argument. The MatchObject
is passed to this function and .group(1)
gives the first parenthesized subgroup:
import re
s = 'start TT end'
callback = lambda pat: pat.group(1).lower()
re.sub(r'([A-Z]){2}', callback, s)
EDIT
And yes, you should use ([A-Z])\1
instead of ([A-Z]){2}
in order to not match e.g. AZ
. (See @bobince's answer.)
import re
s = 'start TT end'
re.sub(r'([A-Z])\1', lambda pat: pat.group(1).lower(), s) # Inline
Gives:
'start t end'
You can't change case in a replacement string. You would need a replacement function:
>>> def replacement(match):
... return match.group(1).lower()
...
>>> re.sub(r'([A-Z])\1', replacement, 'start TT end')
'start t end'