从python上的字符串中删除所有数字 [英] Removing all digits from a string on python
问题描述
所以我需要一些帮助来从这个字符串中删除数字
重新导入
g="C0N4rtist"
re.sub(r'\W','',g)'
print(re.sub(r'\W','',g))
它应该看起来像
CNrtist
但它给了我04
我通过在线研究制作了这段代码,我使用过这个网站 http://docs.python.org/2/library/re.html 寻求帮助.在我看来,代码应该可以工作,而且我不知道出了什么问题,所以让我知道出了什么问题会非常有帮助,因为我已经在网上和 stackoverflow 中进行了研究.
使用 \d
表示数字:
请注意,您不需要为此使用正则表达式,str.translate
与正则表达式版本相比非常快
时间:
<预><代码>>>>g = "C0N4rtist"*100>>>%timeit g.translate(None,digits) #winner100000 个循环,最好的 3 个:每个循环 9.98 us>>>%timeit ''.join(i for i in g if not i.isdigit())1000 个循环,最好的 3 个:每个循环 507 us>>>%timeit re.sub(r'\d+', '', g)1000 个循环,最好的 3 个:每个循环 253 us>>>%timeit ''.join([i for i in g if not i.isdigit()])1000 个循环,最好的 3 个:每个循环 352 us>>>%timeit ''.join([i for i in g if i not in numbers])1000 个循环,最好的 3 个:每个循环 277 usSo 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.
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
这篇关于从python上的字符串中删除所有数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!