getting only the first Number from String in Python

天涯浪子 提交于 2019-12-18 02:47:19

问题


I´m currently facing the problem that I have a string of which I want to extract only the first number. My first step was to extract the numbers from the string.

Headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
print (re.findall('\d+', headline ))
Output is ['27184', '2']

In this case it returned me two numbers but I only want to have the first one "27184".

Hence, I tried with the following code:

 print (re.findall('/^[^\d]*(\d+)/', headline ))

But It does not work:

 Output:[]

Can you guys help me out? Any feedback is appreciated


回答1:


Just use re.search which stops matching once it finds a match.

re.search(r'\d+', headline).group()

or

You must remove the forward slashes present in your regex.

re.findall(r'^\D*(\d+)', headline)



回答2:


Solution without regex (not necessarily better):

import string

no_digits = string.printable[10:]

headline = "redirectDetail('27184','2 -New-York-Explorer-Pass')"
trans = str.maketrans(no_digits, " "*len(no_digits))

print(headline.translate(trans).split()[0])
>>> 27184



回答3:


re.search('[0-9]+', headline).group()


来源:https://stackoverflow.com/questions/32571348/getting-only-the-first-number-from-string-in-python

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