Categories
Python Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *