Delete digits in Python (Regex)


Question

I'm trying to delete all digits from a string. However the next code deletes as well digits contained in any word, and obviously I don't want that. I've been trying many regular expressions with no success.

Thanks!


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

Result:

This must not b deletd, but the number at the end yes

1
16
5/3/2009 1:59:17 PM

Accepted Answer

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)
26
5/3/2009 2:41:34 PM

Try this:

"\b\d+\b"

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


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon