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:
1 2 |
test_string = '1234' print(test_string.isdigit()) # Output: True |
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:
1 2 3 4 5 6 |
test_string = '12.34' try: float(test_string) print(True) except ValueError: print(False) # Output: True |
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:
1 2 3 4 5 6 7 8 |
def is_number(s): if s.isdigit(): return True try: float(s) return True except ValueError: return False |
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
test_string1 = '1234' test_string2 = '12.34' test_string3 = 'Hello' def is_number(s): if s.isdigit(): return True try: float(s) return True except ValueError: return False print(is_number(test_string1)) # Output: True print(is_number(test_string2)) # Output: True print(is_number(test_string3)) # Output: False |
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.