Remove non-numeric characters from a Python string

Asked

Viewed 9,942 times

4

Let’s say, I have:

a = "0LÁM@UN@D0

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

b = "A1B2C3"

Something that takes letters from alphabets and characters, that deletes anything other than numbers (integers) in one string.

I’m using Python 2.7

3 answers

12


You can use regex to solve your problem:

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

# 123
print(b)

Explanation

The function sub(), first receives a pattern in the first parameter, a new string which will be used to replace when you find this pattern in string in the second parameter, and in the last parameter a string that you want to look for the pattern.

Regex

In the first parameter we are passing a regex to remove everything that is not number from the string, a brief explanation about it:

[0-9]: will pick up all digits from 0 to 9

[^0-9] : will take everything that is not digit

  • 3

    Congratulations on your answer. It is common to see here people who try to help, but put answers that exclude your part of the "explanation": they only say "you can use this regex: ..." ...and this does not help much.

  • 3

    @jsbueno Thanks! I know well how it is because I’ve taken this kind of answer a few times hehe.

  • 1

    Marcelo thanks! Please, if possible answer me something. Is if I want to remove only all the special characters?

  • 1

    Thank you Marcelo! : D helped A lot!

5

An alternative to Marcelo’s answer is to make a Join only of the 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'
>>> 
  • Thank you :D!

1

Another possible way to resolve this issue is by using the function filter associated with lambda. This way the code would be:

s = input('Digite uma string: ')
resultado = ''.join(filter(lambda i: i if i.isdigit() else None, s))

print(resultado)

Testing the code:

By executing said code and typing...

A1B2C3

...and press Enter, we will receive as an exit:

123

Browser other questions tagged

You are not signed in. Login or sign up in order to post.