How To Keep Only Numbers In A String Python

While working with strings in Python, you might come across a situation where you need to extract only the numbers present in the string. In this blog post, we will delve into how to keep only the numbers in a string using Python.

Using List Comprehension and join() Method

We can make use of list comprehension to filter out the numbers present in the given string. After extracting the numbers, we join them using the join() method to form a single string containing only the numbers.

Let’s take a look at the following example:

input_string = “Hello123World45″
numbers = ”.join([character for character in input_string if character.isdigit()])
print(numbers)

Output:

        12345
    

Using a For Loop and isdigit() Method

Another approach to achieve this can be using a for loop to iterate through the characters of the given string and checking if the character is a digit using the isdigit() method. If the character is a digit, it is appended to a new string.

Here’s an example:

input_string = “Hello123World45”
numbers = “”

for character in input_string:
if character.isdigit():
numbers += character

print(numbers)

Output:

        12345
    

Using Regular Expressions

Another efficient way to keep only numbers in a string is by using regular expressions. The re module in Python provides functions to work with regular expressions. The findall() function returns a list of matches of a pattern in the given string. We can use the pattern ‘\d+’ to match one or more digits in the input string, and then join the matches to form the final string containing only numbers.

Below is an example using regular expressions to keep only numbers in a string:

import re

input_string = “Hello123World45″
numbers = ”.join(re.findall(‘\d+’, input_string))
print(numbers)

Output:

        12345
    

Conclusion

In this blog post, we have discussed three different methods to keep only numbers in a string in Python. You can choose any of these methods depending upon your requirements and familiarity with the concepts. The list comprehension and join() method is a concise and readable approach, while using regular expressions can be more efficient in some cases, especially when working with complex patterns.