Python extract number from string

Last Updated On Thursday 13th Jan 2022

Extract number from string python

Example 1 : Complete Numbers , Float Numbers

Python Read number from string

  • split() is a built-in python method which is used to split a string into a list.
  • append() is a built-in method in python that adds an item to the end of a list.
	string = "Hello World with 123 Number and Float numbers 1.25 Oh44oh "

num = []
for value in string.split(" "):
    if str.isdigit(value):
        num.append(value)
    else:
        if '.' in value: 
            for digit in value.split('.'):
                if str.isdigit(digit):
                    num.append(digit)
        else: 
            add = 0
            for i in range(len(value)):
                if ord(value[i]) in range(48, 58): 
                    if add > 0:
                        add = (add*10) + int(value[i])
                    else: 
                        add += int(value[i])
                    if i == len(value)-1: 
                        num.append(add)
                else:
                    if add > 0:
                        num.append(add)
                    add = 0

print(num)
	

The Above Code Outputs the

	# ['123', '1', '25', 44]
	

Get Number from String Python

Example 2 : Extract only positive integers

Use the isdigit() inbuilt function to extract the digits from the string and then store them in a list using a list comprehension.The isdigit() function is used to check if a given string contains digits.

	string = "Hello World with 123 numbers and other numbers too 456"
print([int(s) for s in string.split() if s.isdigit()])
	

The Above Code Outputs the

	# [123,456]
	

The Above One is best suited only positive integers. It won’t work for negative integers, floats, or hexadecimal numbers.

Python find number in string

Example 3 : You Can Use Regex

The most effective way us using the regex module. It is easy to use regular Expressions ( RegEx) to determine that a particular string is matched with an identified pattern.findall() is an easy-to-use regex function that returns a list containing all matches.

	import re
print(re.findall(r'\d+', 'Hello World with 123 Number and Float numbers 1.25 Oh44oh '))
	

The Above Code Outputs the

	# ['123', '1', '25', '44']
	

isdigit() and split() functions provide a simpler and more readable code and are faster.