Get number in string python

This is more than a bit late, but you can extend the regex expression to account for scientific notation too.

import re

# Format is [(, ), ...]
ss = [("apple-12.34 ba33na fanc-14.23e-2yapple+45e5+67.56E+3",
       ['-12.34', '33', '-14.23e-2', '+45e5', '+67.56E+3']),
      ('hello X42 I\'m a Y-32.35 string Z30',
       ['42', '-32.35', '30']),
      ('he33llo 42 I\'m a 32 string -30', 
       ['33', '42', '32', '-30']),
      ('h3110 23 cat 444.4 rabbit 11 2 dog', 
       ['3110', '23', '444.4', '11', '2']),
      ('hello 12 hi 89', 
       ['12', '89']),
      ('4', 
       ['4']),
      ('I like 74,600 commas not,500', 
       ['74,600', '500']),
      ('I like bad math 1+2=.001', 
       ['1', '+2', '.001'])]

for s, r in ss:
    rr = re.findall("[-+]?[.]?[\d]+(?:,\d\d\d)*[\.]?\d*(?:[eE][-+]?\d+)?", s)
    if rr == r:
        print('GOOD')
    else:
        print('WRONG', rr, 'should be', r)

Gives all good!

Additionally, you can look at the AWS Glue built-in regex

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Many times, while working with strings we come across this issue in which we need to get all the numeric occurrences. This type of problem generally occurs in competitive programming and also in web development. Let’s discuss certain ways in which this problem can be solved.

    Method #1 : Using List comprehension + isdigit() + split()
    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.

    test_string = "There are 2 apples for 4 persons"

    print("The original string : " + test_string)

    res = [int(i) for i in test_string.split() if i.isdigit()]

    print("The numbers list is : " + str(res))

    Output :

    The original string : There are 2 apples for 4 persons
    The numbers list is : [2, 4]
    

    Method #2 : Using re.findall()
    This particular problem can also be solved using python regex, we can use the findall function to check for the numeric occurrences using matching regex string.

    import re

    test_string = "There are 2 apples for 4 persons"

    print("The original string : " + test_string)

    temp = re.findall(r'\d+', test_string)

    res = list(map(int, temp))

    print("The numbers list is : " + str(res))

    Output :

    The original string : There are 2 apples for 4 persons
    The numbers list is : [2, 4]
    


    In this Python tutorial, we will learn how to find a number in the string by using Python. Also, we will cover these topics.

    • Python find number in string regex
    • Python find value in string
    • Python find first number in string
    • Python find last number in string
    • Python find decimal number in string
    • Python find float number in string
    • Python find largest number in string
    • Python find consecutive numbers in string
    • Python find number of words in string
    • Python find in string reverse
    • Python check if number in string
    • Python find key value in string
    • Python find number of vowels in string
    • In this Program, we will discuss how to find a number in string by using Python.
    • To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

    Syntax:

    Here is the Syntax of str.isdigit() method

    string.isdigit()

    Note: This method does not take any argument and it always returns boolean value true or false.

    Example:

    Let’s take an example and check how to find a number in a string

    new_string = "Germany26China47Australia88"
     
    emp_str = ""
    for m in new_string:
        if m.isdigit():
            emp_str = emp_str + m
    print("Find numbers from string:",emp_str) 

    In the above code, we have created a string and assigned integer and alphabetic characters in it. Now we will use string.isdigit() method and do not pass any argument to it.

    As an output, it returns only integer value that contains in the input string.

    Here is the execution of the following given code

    Get number in string python
    Python find a number in string

    Finding a number in a string by using Python

    Here we can apply the append() and split() method to find a number in a string in Python.

    In Python, the append() function is used to add an element to the end of a list. While the split() function is used to break the string into a list.

    Source Code:

    new_str = "Micheal 89 George 94"
    
    emp_lis = []
    for z in new_str.split():
       if z.isdigit():
          emp_lis.append(int(z))
    
    print("Find number in string:",emp_lis)

    In the above code, we have used a for loop to iterate each word in a list. Now use the str.append() function and pass int(z) with the word to convert it into an integer.

    Once you will print the ’emp_lis’ then the output will display only a list that contains an integer value.

    Here is the Output of the following given code

    Get number in string python
    Python find a number in string

    Read: Python string formatting

    Python find number in string regex

    • Let us see how to find a number in a string by using regular expressions in Python.
    • By using regular expression‘[0-9]+’ with re.findall() method. In Python [0-9] represents finding all the characters which match from 0 to 9 and the + symbol indicates continuous digit characters.
    • In Python, the re.findall() method is used to match the pattern in the string from left to right and it will return in the form of a list of strings.

    Syntax:

    Here is the Syntax of re.findall() method

    re.findall
              (
               pattern,
               string,
               flags=0
              )

    Example:

    Let’s take an example and check how to find a number in a string by using regular expressions in Python.

    import re
    
    new_string = 'Rose67lilly78Jasmine228Tulip'
    new_result = re.findall('[0-9]+', new_string)
    print(new_result)

    In the above code, we have created a string ‘new_string’ in which we have inserted some integer and alphabetic characters. Once you will print the ‘new_result’ then the output will display only integer values in the list.

    Here is the implementation of the following given code

    Get number in string python
    Python find a number in string regex

    Read: Python string to list

    Python find value in string

    • Here we can see how to find a value in a string in Python. To perform this particular task we will apply the combination of split() and str.isdigit() method.
    • In this example, we have created a list by using list comprehension and stored the methods into it. In Python, the str.isdigit() method is used to check if a given string contains digits or not.

    Source Code:

    fin_str = "Bangladesh 2578 England 8349 France 3900"
    
    new_result= [int(m) for m in fin_str.split() if m.isdigit()]
    print("Find value in string:",new_result)

    You can refer to the below Screenshot

    Get number in string python
    Python find value in a string

    Read: Remove character from string Python

    Python find first number in string

    • In this Program, we will discuss how to find a first number in the string by using Python.
    • To do this task we are going to use the re.search() method and this function checks the Pattern at any position in the string and it always returns the first match to the pattern and it takes only two-parameter.

    Syntax:

    Here is the Syntax of re.search() method

    new_val= re.search(pattern, string)

    Source Code:

    import re
    
    new_string = "12James potter"
    new_val= re.search(r"\d", new_string)
    if new_val:
        print("Number found at index", new_val.start())
    else:
        print("Number not found")

    In the above code first, we have created a string ‘new_string’ and then apply the re.search() method on it.

    Now we are going to use the ‘if -else’ condition. If the number contains in a string then it will display the index number. If not then it will display the Number not found.

    You can refer to the below Screenshot

    Get number in string python
    Python find the first number in string

    Read: How to create a string in Python

    Python find last number in string

    • In this section we will discuss how to find the last number in a string by using Python.
    • By using the re.findall() method we can find the last number in a string. To do this task first we will take a string ‘new_str’ and assign integer and alphabet characters to it.
    • Now use the re.findall() method is used to match the pattern in the string from left to right. In this method, there are two parameters pattern and string.

    Example:

    import re
    
    new_str ="73 Japan Germany Paris 36"
    output=re.findall(r'\d+', new_str)[-1]
    print("Last number in string:",output)
     
    new_string = "Elijah Oliva 89" # Another method 
    result= re.search(r"\d", new_string)
    if result:
        print("Number found at index", result.start())
    else:
        print("Number not found")

    In the above code, we have also used the re.search() method to get the index number and this method will check the Pattern at any position in the string.

    Here is the execution of the following given code

    Get number in string python
    Python find the last number in the string

    Read: Python remove substring from a String

    Python find decimal number in string

    • In this Program, we will discuss how to find a decimal number in the string by using Python.
    • To do this task we use the regex module ‘re’ and then create a string in which we have assigned decimal values. Now we will apply the re.findall() method and it will help the user to match the list of characters which includes decimal point numbers.
    • Once you will print the ‘new_output’ then the output will display only decimal values which are available in the given string.

    Source Code:

    import re
    
    new_val = 'Chris67.6Hayden78.1Hemsworth228.2Hayden'
    new_output = re.findall('\d*\.?\d+',new_val)
    print(new_output)

    Here is the execution of the following given code

    Get number in string python
    Python find a decimal number in a string

    Read: Python 3 string replace() method

    Python find float number in string

    • In this section, we will discuss how to find float numbers in the string by using Python.
    • Here you can prefer our previous example that is a decimal number in the string. You can use the re.findall() method to get the decimal or floating numbers in the list.
    • As you can see in the above Screenshot the output list contains only decimal values. In Python floating number represents decimal values.

    Python find largest number in string

    • Here we can see how to find the largest number in a string by using Python.
    • In this example we have use the concept of max() and map() function to find the largest number in string.
    • In Python, the map() function is used for each element of an iterable-like list and it always returns an iterator map object along with that max() function is used to find the largest element in an iterable.
    • In this program first, we have an import regex module along with using the concept ‘[0-9]’+ that represents to find all the characters which match from 0 to 9.

    Example:

    import re
    
    new_string = 'George,146,Micheal,23,John,228,Potter'
    new_result = re.findall('[0-9]+', new_string)
    print("Largest number in string:")
    print (max(map(int, new_result)))

    You can refer to the below Screenshot

    Get number in string python
    Python find the largest number in string

    As you can see in the Screenshot the output is 228.

    Read: Python compare strings

    Python find consecutive numbers in string

    • In this section, we will discuss how to find the consecutive number in a string by using Python.
    • Consecutive numbers mean numbers that follow each other in sequence without space from the smallest number to largest number.
    • Here we will apply the regex module and re.search() method to match the pattern in the String.

    Source Code:

    import re
    
    new_string = "Blue2345green98red"
    i = 4
    new_val = re.search('\d{% s}'% i, new_string)
    new_output = (new_val.group(0) if new_val else '')
    print("Consecutive number in string:")
    print(new_output)

    Here is the Output of the following given code

    Get number in string python
    Python find consecutive numbers in string

    Read: Python find substring in string

    Python find number of words in string

    • Let us see how to find a number of words in the string by using Python.
    • By using the str.split() and len(iterable) method we can easily find the number of words in a string.
    • In Python, the str.split() method splits the string into a list and the len() method returns the length of a string or list. And this method takes only one argument that is an iterable object and this is a built-in function in Python that can be used to measure the length of an iterable object.

    Source Code:

    new_str = "Australia Japan Bangladesh"
    
    new_val = new_str.split()
    count_word = len(new_val)
    print(count_word)

    In the above code first, we have created a string ‘new_str’ and to check how many words are present in a string. We will create a variable ‘new_val’ and apply the function str.split() for breaking the string into a list.

    Now use the len() function to check the length of a string. Once you will print the ‘count_word’ then the output will display the number of words in a string ‘3’.

    Here is the screenshot of the following given code

    Get number in string python
    Python find a number of words in a string

    Read: Slicing string in Python

    Python find in string reverse

    • In this section, we will discuss how to find a string in reverse order by using Python.
    • In this example, we have created a string and an arbitrary index into the string. Now I want to find the index of the second ‘M’ by using the index and str.rfind() method.
    • In this program, we call str.find() method and it will help the user to start checking at index 18. Now within this function, we pass 0 as a parameter and it will start at the beginning of the string.

    Source Code:

    new_str = "Geroge, M,micheal,John,M"
    
    new_indx = 18
    output = new_str.rfind('M', 0, new_indx)
    print(output)

    Here is the execution of the following given code

    Get number in string python
    Python find in string reverse

    As you can see in the Screenshot the output is 8.

    Read: Append to a string Python

    Python check if number in string

    • Here we can see how to check if the number contains in a string by using Python.
    • To perform this particular task we can apply the method str.isdigit() and this method will check the condition if all the integer characters contain in the given string then it will return true otherwise it will return false.

    Syntax:

    Here is the Syntax of str.isdigit() method

    string.isdigit()

    Example:

    Let’s take an example and understand the working of the isdigit() method

    new_string = '835' #integer value
    print(new_string.isdigit())
    
    new_str = 'George'
    print(new_str.isdigit())

    In the above program, we have created a string and assigned an integer value to it. Now use print statement and pass isdigit() method it will display ‘true’ boolean value. Similarly, in the case of string alphabet character, it will display the ‘false’ value.

    Here is the implementation of the following given code

    Get number in string python
    Python checks if a number in a string

    Read: Add string to list Python

    Python find key value in string

    • In this section, we will discuss how to find a key-value pair in a string in Python.
    • By using the regex module we can easily do this task but first, we have to use the re.compile() and dict() method to get the key-value pair from the given string.
    • In Python the re.compile() method is used to compile a regex pattern provided as a string and the dict() method is used to create a dictionary and the dictionary must be unordered.

    Source Code:

    import re
    
    new_val = "China=893 Australia=945"
    result = re.compile(r"\b(\w+)=([^=]*)(?=\s\w+=\s*|$)")
    new_output = dict(result.findall(new_val))
    print(new_output)

    In the above code first, we have created a string ‘new_val’ and then contains equal signs that are escaped out.

    Here is the screenshot of the following given code

    Get number in string python
    Python find key value in a string

    Also, Check: How to concatenate strings in python

    Python find number of vowels in string

    • In this Program, we will discuss how to find a number of vowels in string by using Python.
    • In this example, we will take a string from the user and store it in a variable ‘new_string’. Now use the print statement and assign map function along with lower().count() method and it will print the total number of vowels in the string.

    Source Code:

    new_string = input("Enter the string: ")
    
    print(*map(new_string.lower().count, "aeiou"))

    Here is the Output of the following given code

    Get number in string python
    Python find a number of vowels in a string

    You may like the following Python tutorials:

    • How to split a string using regex in python
    • Check if a list is empty in Python – 39 Examples
    • How to convert list to string in Python
    • Python square a number
    • Python print without newline
    • How to convert an integer to string in python

    In this tutorial, we have learned how to find a number in the string by using Python. Also, we have covered these topics.

    • Python find number in string regex
    • Python find value in string
    • Python find first number in string
    • Python find last number in string
    • Python find decimal number in string
    • Python find float number in string
    • Python find largest number in string
    • Python find consecutive numbers in string
    • Python find number of words in string
    • Python find in string reverse
    • Python find substring in string regex
    • Python check if number in string
    • Python find key value in string
    • Python find number of vowels in string

    Get number in string python

    Python is one of the most popular languages in the United States of America. I have been working with Python for a long time and I have expertise in working with various libraries on Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… I have experience in working with various clients in countries like United States, Canada, United Kingdom, Australia, New Zealand, etc. Check out my profile.

    How do you get a number from a string in Python?

    To find numbers from a given string in Python we can easily apply the isdigit() method. In Python the isdigit() method returns True if all the digit characters contain in the input string and this function extracts the digits from the string. If no character is a digit in the given string then it will return False.

    How do I retrieve a number from a string?

    The number from a string in javascript can be extracted into an array of numbers by using the match method. This function takes a regular expression as an argument and extracts the number from the string. Regular expression for extracting a number is (/(\d+)/).

    How do I extract numbers from a string in a Dataframe Python?

    How to Extract all Numbers from a String Column in Python Pandas.
    Here is how you can run to return a new column with only the numbers: df['Numbers Only'] = df['Numbers and Text'].astype('str').str.extractall('(\d+)').unstack().fillna('').sum(axis=1).astype(int) ... .
    Breakdown. .astype('str') ... .
    .unstack().

    How do you separate an int from a string in Python?

    To split a string into a list of integers:.
    Use the str. split() method to split the string into a list of strings..
    Use the map() function to convert each string into an integer..
    Use the list() class to convert the map object to a list..