Python Forum

Full Version: Find and replace to capitalize with Regex
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I need to capitalize letters that go after a exclamation or question mark and an space.

So this:
'Are you there? yes! perfect'

becomes to this:
'Are you there? Yes! Perfect'

I manage to find them with this pattern ([!?])\s[a-z] but i dont know what to put in the replace so that just the letter become uppercase/capitalize

pattern = '([!?])\s[a-z]'
replace = ''

new_string = re.sub(pattern, replace, text_2)
print(new_string)
Thank you for your help! :)
Change the pattern to ([!?]\s[a-z]).
Now do group 1 match exclamation/question mark and letter.
Then can write a function to use in replacement of re.sub().
import re

def replacement(match):
    return match.group(1).upper()

text_2 = 'Are you there? yes! perfect'
pattern = r'([!?]\s[a-z])'
new_string = re.sub(pattern, replacement, text_2)
print(new_string)
Output:
Are you there? Yes! Perfect
That worked perfectly!

Thank you very much!