In this guide, you’ll learn a simple task that is often times very helpful when working with Python programming: checking if a string is an integer.
This approach can be useful when dealing with user input, data cleaning, or whenever you want to verify the data type of a string entity before performing operations on it.
What is a String?
In Python, a string is a sequence of characters. They are quite versatile, since not only can they contain anything that can be keyed on a keyboard, but it’s also possible to have it contain Unicode characters, or even be empty!
What is an Integer?
An integer, on the other hand, is a whole number: positive or negative, but without decimal points. Python allows you to perform various operations with these integers, including conventional math operations.
How to Check if a String is an Integer in Python
There are several different methods to accomplish this, and here, we’ll be taking a look at the easiest and most straightforward ones.
The first method uses Python’s built-in isdigit() function, which is called so: string.isdigit(). This method returns True if the string contains only digits, otherwise, it returns False.
1 2 3 4 |
def is_int(string): if string.isdigit(): return True return False |
This will give us the correct answer in most cases; however, it does not understand negative numbers, decimal points, or numbers written in scientific notation.
To confirm if our function works, let’s test it with both integers and numbers:
1 2 |
print(is_int("1234")) # should return True print(is_int("abcd")) # should return False |
Full Code:
1 2 3 4 5 6 7 |
def is_int(string): if string.isdigit(): return True return False print(is_int("1234")) # should return True print(is_int("abcd")) # should return False |
Output:
True False
Conclusion:
As seen, checking whether a string is an integer in Python is not a complex task. While the method demonstrated here may not cover all conceivable string-to-integer scenarios, it works perfectly for most practical applications.
For more complex requirements consider using regular expressions, or data-cleaning libraries like Pandas. These tools provide many more sophisticated methods for handling string conversion to integers, including handling edge cases.