Python Forum
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Problem with regex
#1
I want to take:
s = '1 w 2 r 3g'
And format it to:
s = '1 W 2 R 3g'
Based on the concept that the first letter after any space is converted to upper including the first letter.
I tried:
s.title()
but did not get good results. I then tried regex.
pattern = '\s\w|^\w'
re.finditer(pattern, s)
Which found all the matches but I have a problem. Now that is found the matches, how do I convert the matched letters to uppercase? Can someone help me. I tried using indexing but the interpreter gave error that no item assignment is allowed with strings. Immutable. Can someone suggest how I can solve this now that am halfway through?
Reply
#2
This should work
re.sub(r'(?:(?<=\s)|^)\w', lambda m: m.group(0).upper(), s)
Reply


Forum Jump:

User Panel Messages

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