在 Python 中从字符串中去除数字

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30315035/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:13:39  来源:igfitidea点击:

Strip Numbers From String in Python

pythonnltk

提问by ben890

Is there an efficient way to strip out numbers from a string in python? Using nltk or base python?

有没有一种有效的方法可以从python中的字符串中去除数字?使用 nltk 还是基础 python?

Thanks, Ben

谢谢,本

采纳答案by Martin Konecny

Yes, you can use a regular expression for this:

是的,您可以为此使用正则表达式:

import re
output = re.sub(r'\d+', '', '123hello 456world')
print output  # 'hello world'

回答by Rob?

str.translateshould be efficient.

str.translate应该是高效的。

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

To compare str.translateagainst re.sub:

比较str.translate反对re.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

回答by optimcode

Try re.

再试试。

import re
my_str = '123hello 456world'
output = re.sub('[0-9]+', '', my_str)

回答by Doug R.

Here's a method using str.join(), str.isnumeric(), and a generator expression which will work in 3.x:

这是一个使用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!
>>> 

This will also work in 2.x, if you use a unicode string:

如果您使用 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!
>>> 

Hmm. Throw in a paperclip and we'd have an episode of MacGyver.

唔。扔一个回形针,我们就会有一集MacGyver

Update

更新

I know that this has been closed out as a duplicate, but here's a method that works for both Python 2 and Python 3:

我知道这已作为副本关闭,但这里有一种适用于 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!
>>>