Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete digits in Python (Regex)

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

Thanks!


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

Result:

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

like image 665
Menda Avatar asked May 03 '09 13:05

Menda


People also ask

How do you remove digits in Python?

In Python, an inbuilt function sub() is present in the regex module to delete numbers from the Python string. The sub() method replaces all the existences of the given order in the string using a replacement string.

How do you replace a digit in Python?

Method #1 : Using replace() + isdigit() In this, we check for numerics using isdigit() and replace() is used to perform the task of replacing the numbers by K.


2 Answers

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) 
like image 133
oneporter Avatar answered Sep 28 '22 12:09

oneporter


Try this:

"\b\d+\b" 

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

like image 21
jrcalzada Avatar answered Sep 28 '22 12:09

jrcalzada