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"
Asked By: sagi

||

Answers:

Match word boundaries either side of the number

re.sub(r"bd+b", "<num>", text)
Answered By: Iain Shelvington
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.