从字符串中删除数字

时间:2013-05-31 03:01:34

标签: python regex string

我们有一堆字符串,例如:c1309IF1306v1309p1209a1309mo1309
在Python中,删除数字的最佳方法是什么?我需要的只是:上面示例中的cIFvpamo

8 个答案:

答案 0 :(得分:27)

您可以使用regex

>>> import re
>>> strs = "c1309, IF1306, v1309, p1209, a1309, mo1309"
>>> re.sub(r'\d','',strs)
'c, IF, v, p, a, mo'

或更快的版本:

>>> re.sub(r'\d+','',strs)
'c, IF, v, p, a, mo'

timeit比较:

>>> strs = "c1309, IF1306, v1309, p1209, a1309, mo1309"*10**5

>>> %timeit re.sub(r'\d','',strs)
1 loops, best of 3: 1.23 s per loop

>>> %timeit re.sub(r'\d+','',strs)
1 loops, best of 3: 480 ms per loop

>>> %timeit ''.join([c for c in strs if not c.isdigit()])
1 loops, best of 3: 1.07 s per loop

#winner
>>> %timeit from string import digits;strs.translate(None, digits)
10 loops, best of 3: 20.4 ms per loop

答案 1 :(得分:21)

>>> text = 'mo1309'
>>> ''.join([c for c in text if not c.isdigit()])
'mo'

这比正则表达式快

python -m timeit -s "import re; text = 'mo1309'" "re.sub(r'\d','',text)"
100000 loops, best of 3: 3.99 usec per loop
python -m timeit -s "import re; text = 'mo1309'" "''.join([c for c in text if not c.isdigit()])"
1000000 loops, best of 3: 1.42 usec per loop
python -m timeit -s "from string import digits; text = 'mo1309'" "text.translate(None, digits)"
1000000 loops, best of 3: 0.42 usec per loop

str.translate建议@DavidSousa

from string import digits
text.translate(None, digits)

始终是剥离字符最快的。

同样itertools提供了一个名为ifilterfalse

的鲜为人知的函数
>>> from itertools import ifilterfalse
>>> ''.join(ifilterfalse(str.isdigit, text))
'mo'

答案 2 :(得分:13)

我认为字符串方法translate比加入列表等更优雅。

from string import digits # digits = '0123456789'
list1 = ['c1309', 'IF1306', 'v1309', 'p1209', 'a1309', 'mo1309']
list2 = [ i.translate(None, digits) for i in list1 ]

答案 3 :(得分:3)

我认为这是最简单的,也可能是最快的。

>>> import string
>>> s = 'c1309, IF1306, v1309, p1209, a1309, mo1309'
>>> s.translate(None, string.digits)
'c, IF, v, p, a, mo'

注意:str.translate的界面已更改为在python3中使用映射,所以这里是3版本

s.translate({ord(n): None for n in string.digits})

或者更明确的选择:

m = str.maketrans('', '', string.digits)
s.translate(m)

答案 4 :(得分:1)

strings = ['c1309', 'IF1306', 'v1309', 'p1209', 'a1309', 'mo1309']
stripped = [''.join(c for c in s if not c.isdigit()) for s in strings]

答案 5 :(得分:1)

如果您正在处理的所有字符串结束,您可以使用字面strip数字:< / p>

>>> strings = ['c1309', 'IF1306', 'v1309', 'p1209', 'a1309', 'mo1309']
>>> [s.strip("0123456789") for s in strings]
['c', 'IF', 'v', 'p', 'a', 'mo']

如果您要删除字符串末尾的数字,请使用rstrip。如果数字可能出现在字符串中,则此方法根本不起作用。

答案 6 :(得分:0)

如果数字长度固定且位置不在字符串中间,则使用切片表示法。

NUM_LEN = 4
stringsWithDigit = ["ab1234", "cde1234", "fgh5678"]
for i in stringsWithDigit:
   print i[:-NUM_LEN]

其他任何事情

import re
c = re.compile("[^0-9]+")
print c.findall("".join(stringsWithDigit))

答案 7 :(得分:0)

你可以试试这个正则表达式:

^[a-zA-Z]+

它只需要连续的字母from start并忽略字符串中的所有其他内容。

无需更换。