1

Say I have "123asdf". How do I remove all non-integer characters so that it becomes "123"?

2
  • You missed this ?? http://stackoverflow.com/questions/1249388/how-do-we-remove-all-non-numeric-characters-from-a-string-in-python Commented Apr 2, 2014 at 6:48
  • What about characters like #@$ etc? Commented Apr 2, 2014 at 7:02

5 Answers 5

2

You can do:

''.join(x for x in your_string if x.isdecimal())

This takes those characters which are digits and adds them to a string.

Examples

>>> your_string = 'asd8asdf798fad'
>>> print ''.join(x for x in your_string if x.isdecimal())
8798

>>> '1'.isdecimal()
True

>>> 'a'.isdecimal()
False
Sign up to request clarification or add additional context in comments.

Comments

2

I prefer this method:

>>> import re
>>> re.sub(r"\D", "", "123asdf")
'123'

1 Comment

Best method out of all the ones I've found, thank you very much.
1

In Python 2.x, you can use str.translate, like this

data = "123asdf"
import string
print data.translate(None, string.letters)
# 123

Here, the first parameter to str.translate will be mapping of characters saying which character should be changed to what. The second parameter is the string of characters which need to be removed from the string. Since, we don't need to translate but remove alphabets, we pass None to the first parameter and string.letters to the second parameter.

In Python 3.x, you can do

import string
print(data.translate(data.maketrans("", "", string.ascii_letters)))
# 123

Comments

0
>>> s = '123asdf'
>>> filter(str.isdigit, s)
'123'
>>> ''.join(c for c in s if c.isdigit()) # alternate method
'123'

Comments

0

You could use a regex replacement:

>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'

Credits: Removing all non-numeric characters from string in Python

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.