Replace number in a string in python
Question:
Say I have a this string:
text = "bla bl4a 12 bla 23 bla"
I want to replace all the numbers that are not a part of a word with a token <num>
.
I know I can replace all numbers of a string like this:
text = re.sub(r"(d+)", "<num>", text)
Unfortunately this also replace bl4a
with bl<num>a
. This should be the output:
"bla bl4a <num> bla <num> bla"
Answers:
Match word boundaries either side of the number
re.sub(r"bd+b", "<num>", text)
Say I have a this string:
text = "bla bl4a 12 bla 23 bla"
I want to replace all the numbers that are not a part of a word with a token <num>
.
I know I can replace all numbers of a string like this:
text = re.sub(r"(d+)", "<num>", text)
Unfortunately this also replace bl4a
with bl<num>a
. This should be the output:
"bla bl4a <num> bla <num> bla"
Match word boundaries either side of the number
re.sub(r"bd+b", "<num>", text)