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'

Leave a Comment