EN
Python - how to use string replace() method with regex?
1 answers
0 points
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:
xxxxxxxxxx
1
text = "mySampleText"
2
3
result = text.replace("([A-Z])", " $1") # text.replace(regex, regex)
4
5
print(result)
but I receive this:
xxxxxxxxxx
1
mySampleText
instead of this:
xxxxxxxxxx
1
my Sample Text
1 answer
0 points
You can't. Use re.sub()
function instead.
Practical example:
xxxxxxxxxx
1
import re
2
3
text = "mySampleText"
4
5
result = re.sub("([A-Z])", r" \1", text) # re.sub(regex, regex, string)
6
7
print(result)
Output:
xxxxxxxxxx
1
my Sample Text
Note:
Important thing is to change
$1
to\1
and user
specifier to treat the regex as a raw string.
0 commentsShow commentsAdd comment