0
votes

So i need some help on removing the digits from this string

import re

g="C0N4rtist"

re.sub(r'\W','',g)'

print(re.sub(r'\W','',g))

it should look like

CNrtist

but instead it gives me 04

I've made this code from researching online, and i've used this site http://docs.python.org/2/library/re.html for help. In my eyes, the code should work, and i have no clue what's wrong, so letting me know what's wrong would be very helpful as I've already researched online and in stackoverflow.

2
Or just use a generator expression instead of re: print(''.join(x for x in g if not x in "0123456789")) - l4mpi

2 Answers

4
votes

Use \d for digits:

>>> import re
>>> g = "C0N4rtist"
>>> re.sub(r'\d+', '', g)
'CNrtist'

Note that you don't need regex for this, str.translate is very fast compared to the regex version

>>> from string import digits
>>> g.translate(None, digits)
'CNrtist'

Timings:

>>> g = "C0N4rtist"*100
>>> %timeit g.translate(None, digits)      #winner
100000 loops, best of 3: 9.98 us per loop
>>> %timeit ''.join(i for i in g if not i.isdigit())
1000 loops, best of 3: 507 us per loop
>>> %timeit re.sub(r'\d+', '', g)
1000 loops, best of 3: 253 us per loop
>>> %timeit ''.join([i for i in g if not i.isdigit()])
1000 loops, best of 3: 352 us per loop
>>> %timeit ''.join([i for i in g if i not in digits])
1000 loops, best of 3: 277 us per loop
3
votes

There is no need to use regex for this. you can use isdigit() function

   def removeDigitsFromStr(_str):
        result = ''.join(i for i in _str if not i.isdigit())
        return result