How to extract numbers from string in Python?

In my previous article, we have seen how to split a delimited long string to multiple strings and store them in a list. Now we will see how to extract numbers from a string. There is no straightforward way in Python to do this. We have to write our own logic to extract the numbers. Here is one of the method I am following.

This method involved segregating the word from the long sentence, then trying to convert the segrigated word to a float, if it threw error, then catch the exception and pass. if successfully converted, then append the float to a list. This method can extract integers, float and negative numbers and convert them to float. Here is a code sample.

# Assogn a long string to a variable 
some_string = "Some paragraph with 2 to 5 numbers and some float \
    and nagetive numbers like -23 or 32.5 to test the split \
        option in Python version 3.7"

# Logic to get the numbers in a list
numbers = []
for word in some_string.split():
    try:
        numbers.append(float(word))
    except ValueError:
        pass

print(numbers)

Result:

[2.0, 5.0, -23.0, 32.5, 3.7]
extract numbers from string in Python

More Tips

Reference


Leave your thoughts...

This site uses Akismet to reduce spam. Learn how your comment data is processed.