Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getting only the first Number from String in Python

Tags:

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

like image 517
Serious Ruffy Avatar asked Sep 14 '15 18:09

Serious Ruffy


People also ask

How do you extract the first digit of a string in Python?

Making use of isdigit() function to extract digits from a Python string. Python provides us with string. isdigit() to check for the presence of digits in a string. Python isdigit() function returns True if the input string contains digit characters in it.

How do you extract the first number in Python?

To get the first digit, we can use the Python math log10() function. In the loop example, we divided by 10 until we got to a number between 0 and 10. By using the log10() function, we can find out exactly how many times we need to divide by 10 and then do the division directly.

How do I extract numbers from a string in Python?

This problem can be solved by using split function to convert string to list and then the list comprehension which can help us iterating through the list and isdigit function helps to get the digit out of a string.


2 Answers

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) 
like image 82
Avinash Raj Avatar answered Oct 10 '22 10:10

Avinash Raj


re.search('[0-9]+', headline).group() 
like image 34
Dylan Lawrence Avatar answered Oct 10 '22 11:10

Dylan Lawrence