Python Forum
Find and replace to capitalize with Regex
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Find and replace to capitalize with Regex
#1
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! :)
Reply
#2
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
Reply
#3
That worked perfectly!

Thank you very much!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  how to capitalize letter in list object Python iwonkawa 4 207 May-29-2024, 04:29 PM
Last Post: DeaD_EyE
  Regex to find triple characters bfallert 14 574 May-16-2024, 04:02 PM
Last Post: xMaxrayx
  Regex replace in SQLite3 database WJSwan 1 871 Dec-04-2023, 05:55 PM
Last Post: Larz60+
  Working with Excel and Word, Several Questions Regarding Find and Replace Brandon_Pickert 4 1,719 Feb-11-2023, 03:59 PM
Last Post: Brandon_Pickert
  Find numbers using Regex giddyhead 18 3,405 Jul-28-2022, 12:29 AM
Last Post: giddyhead
  Find and Replace numbers in String giddyhead 2 1,325 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  python-docx regex: replace any word in docx text Tmagpy 4 2,359 Jun-18-2022, 09:12 AM
Last Post: Tmagpy
  Find and replace in files with regex and Python Melcu54 0 1,900 Jun-03-2021, 09:33 AM
Last Post: Melcu54
  find an replace not in all entries Monsterherz 1 2,001 Mar-01-2021, 03:59 PM
Last Post: BashBedlam
  How to capitalize in dictionary Inkanus 2 3,805 Oct-28-2020, 01:20 PM
Last Post: Inkanus

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020