Languages

Python - how to use string replace() method with regex?

0 points
Asked by:
Faith-W
383

How can I use string replace() method with regex in Python?

I want to replace every capital letter with the same letter followed by a space character like this:

text = "mySampleText"

result = text.replace("([A-Z])", " $1")  # text.replace(regex, regex)

print(result)

but I receive this:

mySampleText

instead of this:

my Sample Text
1 answer
0 points
Answered by:
Faith-W
383

You can't. Use re.sub() function instead.

Practical example:

import re

text = "mySampleText"

result = re.sub("([A-Z])", r" \1", text)  # re.sub(regex, regex, string)

print(result)

Output:

my Sample Text

Note:

Important thing is to change $1 to \1 and use r specifier to treat the regex as a raw string

0 comments Add comment
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join