Python

How to extract digits from a string? (extract numbers from text)

April 8, 2022

How to extract digits from a string? (extract numbers from text)

In this article we will learn how to extract digits from a string – thus being able to separate numbers from other characters of any text in Python

extract digits from a string thumb

What’s up programmer, ok? Let’s learn how to manipulate strings in Python and separate the numbers from it!

In Python we have the possibility to traverse a string as if it were a list, that is, character by character with a loop

See this example:

text = "9a3b4c5x"

for letter in text:
 print(letter)

We will have the following return:

9
a
3
b
4
c
5
x

Now that we have a way to check each character we just need to validate if it is a digit

And then separate them into a list or do whatever other logic is needed in your software

Let’s implement this check:

text = "9a3b4c5x"
onlyDigits = []

for char in text:
 if char.isdigit():
  onlyDigits.append(char)

print(onlyDigits)

Now the validation done by isdigit() checks whether the character is a digit or not

Then we insert only the digits in the list through the append method

See the end result:

['9', '3', '4', '5']

That way we can separate the digits of a string!

Conclusion

In this article we learned how to extract digits from a string

We submit a string to a “loop for” to iterate through each character in it.

Then we apply a check to see if the character is a digit, finally we add the digits to a list with the append method

Do you want to learn more about Python? Click here!

Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x