getting only the first Number from String in Python

Question:

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

Asked By: Serious Ruffy

||

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)
Answered By: Avinash Raj
re.search('[0-9]+', headline).group()
Answered By: Dylan Lawrence

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
Answered By: David

In my case I wanted to get the first number in the string and the currency too, I tried all solutions, some returned the number without a dot, others returned the number I did like this

priceString = "Rs249.5"

def advancedSplit(unformatedtext):
    custom_numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"]
    priceList = []
    str_length = len(unformatedtext)
    index = 0
    for l in range(len(unformatedtext)):
        if unformatedtext[l] in custom_numbers:
            price = unformatedtext[slice(l, len(unformatedtext))]
            currency = unformatedtext[slice(0,l)]
            priceList.append(currency)
            priceList.append(price)
            break
        elif index == str_length:
            priceList.append("")
            priceList.append("unformatedtext")
            break
        else:
            continue
            
        index += 1
    return priceList
print(advancedSplit(priceString))

to make sure the list will always has len of 2 I added the elif in case the priceString was just "249.5" because I’m using this in web scrape

Answered By: Mahmoud Magdy
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.