7

I have strings like '12454v', '346346z'. I want to delete all letters from strings.

Re works fine:

import re
str='12454v'
re.sub('[^0-9]','', str)

#return '12454'

Is there a way to do this without using regular expressions?

bool.dev
  • 17,508
  • 5
  • 69
  • 93
dr0zd
  • 1,368
  • 4
  • 18
  • 28

5 Answers5

9
>>> ''.join(filter(str.isdigit, '12454v'))
'12454'
Nicolas
  • 5,583
  • 1
  • 25
  • 37
4

In python 2 the second argument to the translate method allows you to specify characters to delete

http://docs.python.org/2/library/stdtypes.html#str.translate

The example given shows that you can use None as a translation table to just delete characters:

>>> 'read this short text'.translate(None, 'aeiou')
'rd ths shrt txt'

(You can get a list of all ASCII letters from the string module as string.letters.)

Update: Python 3 also has a translate method, though it requires a slightly different setup:

from string import ascii_letters
tr_table = str.maketrans({c:None for c in ascii_letters})
'12345v'.transate(tr_table)

For the record, using translation tables in Python 2 is much, much faster than the join/filter method:

>>> timeit("''.join(filter(lambda c:not c.isalpha(), '12454v'))")
2.698641061782837
>>> timeit("''.join(filter(str.isdigit, '12454v'))") 
1.9351119995117188
>>> timeit("'12454v'.translate(None, string.letters)", "import string")
0.38182711601257324

Likewise in Python 3:

>>> timeit("'12454v'.translate(tr_table)", "import string; tr_table=str.maketrans({c:None for c in string.ascii_letters})")
0.6507143080000333
>>> timeit("''.join(filter(lambda c:not c.isalpha(), '12454v'))")
2.436105844999929
kojiro
  • 74,557
  • 19
  • 143
  • 201
2

I think you can try this with .translate method.

>>> import string
>>> str='12454v'
>>> str.translate(None, string.letters)
'12454'

There is a very good answer about .translate method here.

Community
  • 1
  • 1
Ye Lin Aung
  • 11,234
  • 8
  • 45
  • 51
1

This is a somewhat less elegant than the others because it's not using a specific function and is somewhat more clunky:

newStr = ''
myStr='12454v'
for char in myStr:
    try:
        newStr += str(int(char))
    except ValueError:
        pass
print newStr

Again, this isn't best way, but I'm just throwing it out there. I converted it to an int first so that it can check whether or not is an integer. Then, I convert it to a str so that it can be added to newStr.

On another note, you shouldn't use str as a variable name because it shadows the built-in function str().

Rushy Panchal
  • 16,979
  • 16
  • 61
  • 94
0

For Python 3.10 I had to do the following:

import string
l = string.ascii_letters
trans = "".maketrans(l, l, l)
s = "123abc"
s = s.translate(trans)
nikhilweee
  • 3,953
  • 1
  • 18
  • 13