Remove non-numeric characters from a string in Python

3

Let's suppose, I have:

a = "0LÁM@UN@D0

I would like something that removes all the letters (A-Z) and other characters, I just want the numbers to stay in the example, it would only be 0 and 0

b = "A1B2C3"

Something that takes away the letters of the alphabets and characters, which delete everything other than integers in a string .

I'm using Python 2.7

    
asked by anonymous 12.11.2017 / 19:04

2 answers

9

You can use regex to solve your problem:

import re
b = "A1B2C3"
b = re.sub('[^0-9]', '', b)

# 123
print(b)

Explanation

The sub() function first gets a pattern in the first parameter, a new string that will be used to override when it finds that pattern in string in the second parameter, and in the last parameter to string want to look for the pattern.

Regex

In the first parameter we are passing a regex to remove anything other than string number, a brief explanation about it:

[0-9] : will get all digits from 0 to 9

[^0-9] : will catch anything other than a digit

    
12.11.2017 / 19:28
1

An alternative to Marcelo's answer is to make a join of just a digit:

>>> a = "0LÁM@UN@D0"
>>> b = "A1B2C3"
>>> ''.join(c for c in a if c.isdigit())
'00'
>>> ''.join(c for c in b if c.isdigit())
'123'
>>> 
    
13.11.2017 / 14:09