dr0zd
dr0zd

Reputation: 1378

Delete letters from string

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?

Upvotes: 7

Views: 3040

Answers (5)

nikhilweee
nikhilweee

Reputation: 4519

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)

Upvotes: 0

kojiro
kojiro

Reputation: 77099

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

Upvotes: 4

Rushy Panchal
Rushy Panchal

Reputation: 17532

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().

Upvotes: 1

Ye Lin Aung
Ye Lin Aung

Reputation: 11459

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.

Upvotes: 2

Nicolas
Nicolas

Reputation: 5668

>>> ''.join(filter(str.isdigit, '12454v'))
'12454'

Upvotes: 9

Related Questions