How to Check If a String is a Number in Python

In Python, strings are often used in a variety of functions, and sometimes we need to check whether a given string can be actually converted to numbers, be it integers or floats.

This verification allows for more robust codes, as it can prevent unpredictable behaviors caused by wrong data types. In this tutorial, we’ll cover some easy ways to validate if a string is a number in Python.

Step 1: Check If a String is an Integer

The simplest way to check if a string is a number, more specifically an integer, is to use the isdigit() method. This method returns True if all the characters in the string are digits. If not, it returns False. Here’s an example:

Step 2: Check If a String is a Float

For checking if a string is a float, we’ll have to be a bit creative as Python doesn’t offer a built-in method. However, we can try to convert the string to float using the float() function. If the function runs without error, it indicates that the string can be regarded as a float. We can do this within a try…except block:

Step 3: Combining the Methods

We can combine both methods in a function in order to check if a string can be converted to an integer or a float:

Full Code

Conclusion

Using these simple methods, Python allows us to easily validate if a string can be converted to a number. This can be very handy in a variety of scenarios, especially when dealing with user inputs or while parsing data. Keep in mind that these methods only work for positive numbers. For dealing with negative numbers, you would have to implement additional checks.