Sometimes, we want to check if string input is a number with Python.
In this article, we’ll look at how to check if string input is a number with Python.
How to check if string input is a number with Python?
To check if string input is a number with Python, we can try to parse the string into a number.
For instance, we write
try:
val = int(user_input)
except ValueError:
print("Not an int")
to parse user_input
into an int with int
.
If it can’t be parsed into an int, a ValueError
will be raised.
And we catch it and print 'Not an int'
if that’s the case.
Conclusion
To check if string input is a number with Python, we can try to parse the string into a number.