How to remove characters except digits from string in Python?

PythonServer Side ProgrammingProgramming

We have a variety of ways to achieve this. We can filter out non digit characters using for ... if statement. For example:

>>> s = "H3ll0 P30P13"
>>> ''.join(i for i in s if i.isdigit())
'303013'

We can also use filter and a lambda function to filter out the characters. For example:

>>> s = "H3ll0 P30P13"
>>> filter(lambda x: x.isdigit(), s)
'303013'

Though an overkill for such a simple task, we can also use a regex for achieving the same thing. The \D character(non digit) can be replaced by an empty string. For example:

>>> import re
>>> s = "H3ll0 P30P13"
>>> re.sub("\D", "", s)
'303013'
raja
Published on 14-Dec-2017 10:47:48
Advertisements