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
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:
- Convert floating point number to fixed point in Python
- What is %matplotlib inline and how to use ?
- Increase the cell width of the Jupyter Notebook in browser
- Add python3 kernel to jupyter IPython notebook ?
- Reset jupyter notebook theme to default theme
- How to change the default theme in Jupyter Notebook ?
- Change the Jupyter Notebook startup folder in Windows & Mac
- To run Jupyter Notebook on Windows from command line
- Run a Jupyter Notebook .ipynb file from terminal or cmd prompt
- Amazon Linux AMI : apt-get command not found
- Check if a file or folder exists without getting exceptions ?
- Python program to find the greatest of three numbers
- Check Given Number is Odd or Even using Python
- Find which users belongs to a specific group in linux
- Embed HTML within IPython Notebook
- Check if Python Object is a Number ?
- Error: helm install unknown flag: –name
- Install Python 3 on Windows 10 machine
- Convert negative to positive number in Python
- TypeError: a bytes-like object is required, not ‘str’ – Python3
- Extract numbers from a string in python