Removing all digits from a string on python

后端 未结 2 1652
不知归路
不知归路 2020-12-22 06:29

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

import re

g=\"C0N4rtist\"

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

相关标签:
2条回答
  • 2020-12-22 06:55

    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
    
    0 讨论(0)
  • 2020-12-22 06:57

    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
    
    0 讨论(0)
提交回复
热议问题