您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

从Python上的字符串中删除所有数字

从Python上的字符串中删除所有数字

使用\d的数字:

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

请注意,您不需要正则表达式,str.translate与正则表达式版本相比非常快

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

>>> 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
python 2022/1/1 18:34:30 有212人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶