Delete digits in Python (Regex) Delete digits in Python (Regex) python python

Delete digits in Python (Regex)


Add a space before the \d+.

>>> s = "This must not b3 delet3d, but the number at the end yes 134411">>> s = re.sub(" \d+", " ", s)>>> s'This must not b3 delet3d, but the number at the end yes '

Edit: After looking at the comments, I decided to form a more complete answer. I think this accounts for all the cases.

s = re.sub("^\d+\s|\s\d+\s|\s\d+$", " ", s)


Try this:

"\b\d+\b"

That'll match only those digits that are not part of another word.


Using \s isn't very good, since it doesn't handle tabs, et al. A first cut at a better solution is:

re.sub(r"\b\d+\b", "", s)

Note that the pattern is a raw string because \b is normally the backspace escape for strings, and we want the special word boundary regex escape instead. A slightly fancier version is:

re.sub(r"$\d+\W+|\b\d+\b|\W+\d+$", "", s)

That tries to remove leading/trailing whitespace when there are digits at the beginning/end of the string. I say "tries" because if there are multiple numbers at the end then you still have some spaces.