import re
re.sub('\\baword\\b', lambda m: m.group(0)[0].lower() == m.group(0)[0] and
    'bword' or 'Bword', 'Aword aword', flags=re.I)
How do I write a regex to replace a word but keep its case in Python?