1

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

mango
  • 1,183
  • 6
  • 17
  • 33

5 Answers5

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
Community
  • 1
  • 1
sshashank124
  • 31,495
  • 9
  • 67
  • 76
2

I prefer this method:

>>> import re
>>> re.sub(r"\D", "", "123asdf")
'123'
anon582847382
  • 19,907
  • 5
  • 54
  • 57
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
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
0
>>> s = '123asdf'
>>> filter(str.isdigit, s)
'123'
>>> ''.join(c for c in s if c.isdigit()) # alternate method
'123'
Jayanth Koushik
  • 9,476
  • 1
  • 44
  • 52
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

Community
  • 1
  • 1
Benjamin Toueg
  • 10,511
  • 7
  • 48
  • 79