Say I have "123asdf". How do I remove all non-integer characters so that it becomes "123"?
5 Answers
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
Comments
I prefer this method:
>>> import re
>>> re.sub(r"\D", "", "123asdf")
'123'
1 Comment
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
You could use a regex replacement:
>>> import re
>>> re.sub("[^0-9]", "", "sdkjh987978asd098as0980a98sd")
'987978098098098'
Credits: Removing all non-numeric characters from string in Python
http://stackoverflow.com/questions/1249388/how-do-we-remove-all-non-numeric-characters-from-a-string-in-python