How to Extract Numbers from a String in Python?

In this tutorial, I will explain how to extract numbers from a string in Python. As a data scientist working for a USA-based company, I often encounter strings that contain both text and numbers. In such cases, I need to extract the numbers from the string for further analysis. Then, I explored more about this topic and found some important methods. I will share my findings in this article with examples.

Extract Numbers from a String in Python

Python provides several ways to extract numbers from a string. Let’s learn some of the most common methods with examples.

Read Convert Int to Bytes in Python

Method 1. Use Regular Expressions (re)

One of the most useful ways to extract numbers from a string is by using regular expressions (regex). The re module in Python allows you to search for specific patterns within a string. Here’s an example:

import re

text = "Emma Watson, born on April 15, 1990, in Paris, moved to Oxford, UK, OX1 2JD in 2010."
numbers = re.findall(r'\d+', text)

print(numbers)

Output:

['15', '1990', '1', '2', '2010']

I have executed the above example code and added the screenshot below.

Extract Numbers from a String in Python

In this example, re.findall() searches for all occurrences of one or more digits (\d+) in the string and returns them as a list of strings. The r before the pattern indicates a raw string, which avoids issues with escape characters.

Read Convert DateTime to UNIX Timestamp in Python

Method 2. Use list comprehension and isdigit()

Another way to extract numbers from a string is by using a combination of list comprehension and the isdigit() method in Python. Here’s an example:

text = "Liam Olivia Noah Emma Oliver Charlotte Elijah Amelia William Sophia James Isabella Benjamin Mia Lucas Ava Henry Evelyn Alexander Harper"
numbers = [int(word) for word in text.split() if word.isdigit()]

print(numbers)

Output:

[]

I have executed the above example code and added the screenshot below.

How to Extract Numbers from a String in Python

In this example, we split the string into a list of words using split(). Then, we use list comprehension to iterate over each word and check if it consists only of digits using isdigit(). If a word is a valid number, we convert it to an integer int() and include it in the resulting list.

Read Concatenate String and Float in Python

Method 3. Use join() and filter()

You can also use a combination of Python’s join(), filter(), and isdigit() to extract numbers from a string. Here’s an example:

text = "Michael Smith lives at 123 Main St, Anytown, CA 98765, USA."
numbers = ''.join(filter(lambda x: x.isdigit(), text))

print(numbers)

Output:

12398765

I have executed the above example code and added the screenshot below.

Extract Numbers from a String in Python join() and filter()

In this example, filter() is used with a lambda function to select only the characters that are digits using isdigit(). The resulting characters are then joined together into a single string using join().

Read How to Find the Largest and Smallest Numbers in Python?

Handle Real-World Scenarios

In real-world scenarios, you might encounter more complex strings that require additional processing. For example, consider the following string:

"The new iPhone 13 Pro costs $999, while the iPhone 13 Mini starts at $699. Apple's headquarters is located at One Apple Park Way, Cupertino, CA 95014, USA."

To extract all the numbers from this string, including those with special characters like “$”, you can use a more sophisticated regular expression:

import re

text = "The new iPhone 13 Pro costs $999, while the iPhone 13 Mini starts at $699. Apple's headquarters is located at One Apple Park Way, Cupertino, CA 95014, USA."
numbers = re.findall(r'[$]?\d+', text)

print(numbers)

Output:

['$999', '$699', '95014']

In this example, the regular expression [$]?\d+ matches optional “$” characters followed by one or more digits, allowing you to extract numbers with leading “$” symbols.

Read How to Check if a Python String Contains a Substring?

Conclusion

In this tutorial, I have explained how to extract numbers from a string in Python. I discussed some methods including regular expressions, list comprehension with isdigit(), and a combination of join(), filter(), and isdigit(). I also discussed how to handle real-world scenarios.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.