Languages

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

0 points
Asked by:
Faith-W
503

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:

but I receive this:

instead of this:

1 answer
0 points
Answered by:
Wayne
475

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

Practical example:

Output:

Note:

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

0 commentsAdd comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
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