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
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"]