Kodeclik Blog
Can your Python string be an integer?
Suppose you are given a Python string such as “123”. Can your string be interpreted as an integer? (The answer here is Yes). How can we write code for this purpose? Here are 4 ways to do so.
Method 1: Use the isnumeric() method
Consider the following code:
str1 = "314"
print(str1.isnumeric())
This outputs:
True
The way isnumeric() works is to look at each character of the string and check if that character is a numeric (typically numbers from 0 to 9 but some special characters are also allowed).
This means that “3.14”, which even though is a number, would not be considered a number for isnumeric() purposes because it contains a period. If we do:
str1 = "3.14"
print(str1.isnumeric())
it returns:
False
Similarly, with the below code:
str1 = "-314"
print(str1.isnumeric())
we will get:
False
even though -314 is a numeric (and an integer). Thus isnumeric() has limitations.
The special characters that are indeed allowed by isnumeric() involve fractions and superscript/subscript notation.
Method 2: Use the isdigit() method
The isdigit() method is very similar to isnumeric(). Let us try:
str1 = "314"
str2 = "3.14"
str3 = "-314"
print(str1.isdigit())
print(str2.isdigit())
print(str3.isdigit())
The outputs are:
True
False
False
Note that the outputs are exactly the same as those of isnumeric(). What is the difference between these methods then?
isdigit() is just like isnumeric() in that it only recognizes numbers, superscripts, and subscripts. But it is different from isnumeric() in that it doesn’t recognize fractions. So again this approach has limitations for our needs.
Method 3: Construct your own regular expression
This is a fool-proof way to check if a given string is an integer. We construct a regular expression that allows for an optional sign (plus or minus symbol) followed by a series of digits. Here is how this works:
import re
def isinteger(x):
if re.match("^[-+]?\d+$",x) is not None:
return True;
else:
return False;
str1 = "314"
str2 = "3.14"
str3 = "-314"
print(isinteger(str1))
print(isinteger(str2))
print(isinteger(str3))
Note that in the above code, we first import “re”, a regular expression module. Then we construct a function called isinteger that takes a string as input (x) and checks if it matches the given template. The template specifies that it must begin with either a plus or minus sign (optional, as indicated by the “?” sign). Then we look for one or more digits. The presence of the “$” sign ensures that there are no more characters in the string. If the match succeeds, the re.match() expression will return the position it was found and the span information. For our purposes we just want to confirm that it returns something other than None in which case the function returns True. Else it returns False.
Note that because this is a function (and not a method), we pass the string as an argument to the function isinteger() to obtain our results. The output is:
True
False
True
Method 4: Use int() exception handling
The final approach we will learn is to use the casting operator int() that converts its input to an integer. If this works, the function returns True; else it returns False. Consider the following code:
def isinteger(x):
try:
converted_x = int(x)
return True
except ValueError:
return False
str1 = "314"
str2 = "3.14"
str3 = "-314"
print(isinteger(str1))
print(isinteger(str2))
print(isinteger(str3))
As you can see, in the definition of the function isinteger, we first aim to convert the given input (from a string) to an integer. If this succeeds the function returns True, else it raises an exception which is handled by returning False. The program’s output is:
True
False
True
as desired.
So we have seen four approaches to check if a given string is an integer. The first two methods are not exhaustive but might suffice if your integer containing string is not expected to have signs. The second two methods are more elaborate and will work for all scenarios.
If you liked learning about the different ways to check if a string can be an integer, you will like our post on the Python str() function which covers how you can convert integers and other data types to strings.
Interested in more things Python? See our blogpost on Python's enumerate() capability. Also if you like Python+math content, see our blogpost on Magic Squares. Finally, master the Python print function!
Want to learn Python with us? Sign up for 1:1 or small group classes.