Remove non-numeric characters from string in Python

How to remove non-numeric characters from string in Python ?

This tutorial guides you on how to remove non-numeric characters from string in Python programming language. We can extract only digits from string which has numeric characters also in numerous ways. Let’s see how to do that in the below sections.

Remove non-numeric characters from string in Python

Remove non-numeric characters from string in Python

First way is using regex library and re.sub() method. The syntax for re.sub() is as follows:

Syntax:

re.sub(pattern, repl, string, count=0, flags=0)

This function returns the string obtained by replacing the leftmost non-overlapping occurrences of pattern in string by the replacement repl. Note, if the pattern is not found then the string is unchanged.

For example,

import re
re.sub("[^0-9]", "", "abcdef123456a0123xyz987uvw567ox")

Output

'1234560123987567'

Using Python String’s join() and isdigit() methods

In this approach we will be using Python String methods join() and isdigit() to remove non-numeric characters from String.

For Example,

''.join(s for s in "abcdef123456a0123xyz987uvw567ox" if s.isdigit())

Output

'1234560123987567'

Alternatively, you can using digits module and achieve the same as shown below.

from string import digits
''.join(s for s in "abcdef123456a0123xyz987uvw567ox" if s in digits)

Output

'1234560123987567'

Using join() and filter() functions

In the following example we have used both join() and filter() function to print only digits.

For instance,

def printnumeric(num_seq):
    num_seq_type= type(num_seq)
    return num_seq_type().join(filter(num_seq_type.isdigit, num_seq))

Output

>>> print(printnumeric("abcdef123456a0123xyz987uvw567ox"))

1234560123987567

That’s it. Finally, you had learnt numerous ways to remove non-numeric characters from string in Python programming language.

Hope it helped 🙂

You’ll also like:

References

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments