Menu Close

How to check if a string is a number with Python?

Sometimes, we want to check if a string is a number with Python.

In this article, we’ll look at how to check if a string is a number with Python.

How to check if a string is a number with Python?

To check if a string is a number with Python, we can use the string’s isdigit method.

For instance, we write:

a = "03523"
print(a.isdigit())

b = "03523abc"
print(b.isdigit())

We call isdigit on a, which is a number string, so the first print call should print True.

Then we call isdigit on b, which isn’t a number string, so the 2nd print call should print False.

Conclusion

To check if a string is a number with Python, we can use the string’s isdigit method.

Posted in Python, Python Answers