0

我有一些字符串,例如-

1. "07870 622103"
2. "(0) 07543 876545"
3. "07321 786543 - not working"

我想得到这些字符串的最后 10 位数字。喜欢 -

1. "07870622103"
2. "07543876545"
3. "07321786543"

到目前为止,我已经尝试过——

a = re.findall(r"\d+${10}", mobilePhone)

请帮忙。

4

2 回答 2

3

过滤你的字符串中的数字并挑选出最后 10 个会更容易:

''.join([c for c in mobilePhone if c.isdigit()][-10:])

结果:

>>> mobilePhone = "07870 622103"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7870622103'
>>> mobilePhone = "(0) 07543 876545"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7543876545'
>>> mobilePhone = "07321 786543 - not working"
>>> ''.join([c for c in mobilePhone if c.isdigit()][-10:])
'7321786543'

正则表达式方法(过滤除数字以外的所有内容)更快:

$ python -m timeit -s "mobilenum='07321 786543 - not working'" "''.join([c for c in mobilenum if c.isdigit()][-10:])"
100000 loops, best of 3: 6.68 usec per loop
$ python -m timeit -s "import re; notnum=re.compile(r'\D'); mobilenum='07321 786543 - not working'" "notnum.sub(mobilenum, '')[-10:]"
1000000 loops, best of 3: 0.472 usec per loop
于 2012-11-28T10:01:44.817 回答
2

我建议使用正则表达式来丢弃所有非数字。像这样:

newstring = re.compile(r'\D').sub('', yourstring)

正则表达式非常简单 -\D表示非数字。上面的代码用于sub用空字符串替换任何非数字字符。所以你得到你想要的newstring

哦,为了获取最后十个字符,请使用newstring[-10:]

那是一个正则表达式的答案。Martijn Pieters 的答案可能更 Pythonic。

于 2012-11-28T10:03:34.967 回答