问题
Is there a better (more efficient) way to find x-digit number (number consisted of x digits) in a text?
My way:
EDIT:
for n in range(0,len(text)):
if isinstance(text[n:n+x], (int)) and isinstance(text[n:n+x+1] is False:
result = text[n:n+x]
return result
EDIT 2:
for n in range(0,len(text)):
try:
int(text[n:n+x])
result = text[n:n+x]
except:
pass
return result
回答1:
import re
string = "hello 123 world 5678 897 word"
number_length = 3
pattern= r"\D(\d{%d})\D" % number_length # \D to avoid matching 567
print re.findall(pattern, string)
output
["123","897"]
回答2:
You could use regex to achieve that. For example
>>> import re
>>> s = "abc 123 45678"
>>> re.search("(\d{5})\D",s).group()
'45678'
finds a 5 digit number in s. Or if you have multiple numbers use findall
>>> s = "abc 123 45678\nbla foo 65432"
>>> re.findall("(\d{5})\D",s)
['45678', '65432']
回答3:
exampleText = "abcd12345xyz"
import re
match = re.search('\d+',exampleText)
print(match.group())
来源:https://stackoverflow.com/questions/25532877/find-x-digit-number-in-a-text-using-python