Find and replace to capitalize with Regex - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Find and replace to capitalize with Regex (/thread-25136.html) |
Find and replace to capitalize with Regex - hermobot - Mar-21-2020 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! :) RE: Find and replace to capitalize with Regex - snippsat - Mar-21-2020 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)
RE: Find and replace to capitalize with Regex - hermobot - Mar-21-2020 That worked perfectly! Thank you very much! |