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
  Regex replace in SQLite3 database WJSwan 1 747 Dec-04-2023, 05:55 PM
Last Post: Larz60+
  Working with Excel and Word, Several Questions Regarding Find and Replace Brandon_Pickert 4 1,492 Feb-11-2023, 03:59 PM
Last Post: Brandon_Pickert
  Find numbers using Regex giddyhead 18 3,010 Jul-28-2022, 12:29 AM
Last Post: giddyhead
  Find and Replace numbers in String giddyhead 2 1,197 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  python-docx regex: replace any word in docx text Tmagpy 4 2,139 Jun-18-2022, 09:12 AM
Last Post: Tmagpy
  Find and replace in files with regex and Python Melcu54 0 1,824 Jun-03-2021, 09:33 AM
Last Post: Melcu54
  find an replace not in all entries Monsterherz 1 1,913 Mar-01-2021, 03:59 PM
Last Post: BashBedlam
  How to capitalize in dictionary Inkanus 2 3,616 Oct-28-2020, 01:20 PM
Last Post: Inkanus
  Regex won't replace character with line break Tomf96 2 2,500 Jan-12-2020, 12:14 PM
Last Post: Tomf96
  [split] capitalize dict keys for display in string newbieAuggie2019 3 2,936 Oct-10-2019, 10:50 AM
Last Post: perfringo

Forum Jump:

User Panel Messages

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