Find x-digit number in a text using Python

為{幸葍}努か 提交于 2021-02-16 09:22:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!