Python中如何从字符串中删除数字

12

有没有一种有效的方式在Python中从字符串中去除数字?可以使用nltk或基本的Python方法吗?

谢谢, Ben


你能提供一个你想要做的例子吗? - MAK
如果我有一个字符串,比如说: x = “我有3只狗” 我想要一种方法将x转换为: “我有狗” - ben890
2
вҖңжҲ‘жңү3еҖҚдәҺ2еҸӘзҢ«зҡ„зӢ—вҖқжҳҜд»Җд№Ҳж„ҸжҖқпјҹ - Jon Clements
3
“或者...”左转第一条路,然后右转第二条路,接着你要找的公司叫TRG1,在这条路上大约往前走100米 - 如果你懒得走,你可以坐公交车,票价为2.5英镑。” - Jon Clements
在这里查看其他好的答案:https://dev59.com/Rmcs5IYBdhLWcg3wcDiZ - tommy.carstensen
3个回答

38
可以使用正则表达式解决此问题:
import re
output = re.sub(r'\d+', '', '123hello 456world')
print output  # 'hello world'

这太完美了!谢谢Martin。 - ben890
使用正则表达式解决问题是不会出错的,因为它也可以很好地应用于其他情况(比如说他想要删除旁边的字母)。 - Alex Huszagh
最佳答案。像魔法一样运作。 - Kareem Khaleel

15

str.translate 应该是高效的。

In [7]: 'hello467'.translate(None, '0123456789')
Out[7]: 'hello'

为了比较str.translatere.sub

In [13]: %%timeit r=re.compile(r'\d')
output = r.sub('', my_str)
   ....: 
100000 loops, best of 3: 5.46 µs per loop

In [16]: %%timeit pass
output = my_str.translate(None, '0123456789')
   ....: 
1000000 loops, best of 3: 713 ns per loop

问题是:str.translate有点难以同时兼容2.x/3.x :( - Jon Clements
7
在Python 3.x中,您需要使用my_str.translate({ord(ch): None for ch in '0123456789'})来实现对字符串中数字的删除。 - Jon Clements
我想知道 r.sub() 需要多长时间?比如,在你想要在多个字符串上执行此操作并且已经预编译了正则表达式的条件下。 - Ross
@Ross - 从我在答案中放置的代码来看,大约为5.46微秒。 - Robᵩ
2
@Rob - 啊,我错过了第一行是设置行。从一些最佳/最坏情况的翻译中看来,在最坏情况下,translate 的表现要好得多。使用 'python -m timeit',我发现以下有利于 translate; '123hello 456world' - x5.0 '1234567890987654321012345678909876543210' - x17.0 '5a$%&^@)9lhk45g08j%Gmj3g09jSDGjg0034k' - x9.0 'hello world im your boss' - x 1.8 - Ross

1

以下是一种使用 str.join(), str.isnumeric() 和生成器表达式的方法,适用于 3.x 版本:

>>> my_str = '123Hello, World!4567'
>>> output = ''.join(c for c in my_str if not c.isnumeric())
>>> print(output)
Hello, World!
>>> 

如果您使用Unicode字符串,这也适用于2.x版本:
>>> my_str = u'123Hello, World!4567'
>>> output = ''.join(c for c in my_str if not c.isnumeric())
>>> print(output)
Hello, World!
>>> 

嗯。再扔进一根回形针,我们就有了一集《百战天龙》。

更新

我知道这已经被归为重复问题了,但是这里有一个适用于Python 2和Python 3的方法:

>>> my_str = '123Hello, World!4567'
>>> output = ''.join(map(lambda c: '' if c in '0123456789' else c, my_str))
>>> print(output)
Hello, World!
>>>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接