How to Check Number Types and Converting Strings to Numbers in Python
This guide covers how to determine if a Python variable is an integer (int
) or a floating-point number (float
). It also explains how to check if a string can be safely converted to an integer or a float, and how to verify if a float represents a whole number.
Checking if a Number is an int
or float
To determine if a variable that already holds a number (not a string) is an integer or a float, use the isinstance()
function.
my_num = 1357
if isinstance(my_num, int):
print('number is int') # Output: number is int
if isinstance(my_num, float):
print('number is float') # No output
isinstance(object, classinfo)
: ReturnsTrue
if theobject
is an instance ofclassinfo
(or a subclass of it),False
otherwise.
Handling Booleans
Be aware that booleans (True
and False
) are subclasses of integers in Python:
print(isinstance(True, int)) # Output: True
print(isinstance(False, int)) # Output: True
If you need to distinguish between actual integers and booleans, you can add an explicit check:
my_num = True
if isinstance(my_num, int) and not isinstance(my_num, bool):
print("It's an integer, and not a boolean")
else:
print("It's a boolean") # Output: It's a boolean
- The
isinstance(my_num, int) and not isinstance(my_num, bool)
can be used to check if the number is an integer, and not a boolean.
Checking for Either int
or float
To check if a variable is either an integer or a float, pass a tuple of types to isinstance()
:
my_num = 1357.0
if isinstance(my_num, (int, float)):
print('Number is either int or float') # Output: Number is either int or float
Using type()
You can also use the type()
function to get the type of the variable. While isinstance()
is generally preferred (because it handles inheritance correctly), type()
can be useful for simple checks:
my_num = 1357
print(type(my_num)) # Output: <class 'int'>
my_num_2 = 3.14
print(type(my_num_2)) # Output: <class 'float'>
Checking if a String Can Be Converted to a Number
The more common and challenging scenario is determining if a string can be converted to an integer or a float.
Checking for Integers with try-except
(Recommended)
The most robust and Pythonic way to check if a string can be converted to an integer is to attempt the conversion and handle the potential ValueError
:
def can_convert_to_int(string):
try:
int(string) # Try to convert
return True
except ValueError:
return False
print(can_convert_to_int('1357')) # Output: True
print(can_convert_to_int('-1357')) # Output: True (handles negative numbers)
print(can_convert_to_int('1.357')) # Output: False (not a valid integer)
print(can_convert_to_int('ABC123')) # Output: False
- This approach is known as "Easier to Ask for Forgiveness than Permission" (EAFP). It's a common and efficient Python idiom.
- If a
ValueError
is raised during theint()
conversion, theexcept
block is executed. - If no exception is thrown, the method returns True.
- This correctly handles negative integers and non-numeric strings.
Checking for Integers with isdigit()
(Limited)
The isdigit
method can also be used to test whether a string can be converted to an integer, but it is only reliable with positive integer numbers.
my_str = '1234'
if my_str.isdigit():
my_int = int(my_str)
print(my_int) # Output: 1234
print('✅ string can be converted to integer')
else:
print('⛔️ string CAN NOT be converted to integer')
isdigit()
returnsTrue
only if all characters in the string are digits and the string is not empty. It returnsFalse
for negative numbers, decimals, or any other non-digit characters.- This is a quick test if the string could be an integer (but doesn't guarantee it).
Limitations of isdigit()
: It doesn't handle negative signs (-
) or decimal points (.
). Therefore, "-123".isdigit()
and "3.14".isdigit()
both return False
. Only use isdigit()
if you are certain your strings will only contain non-negative integer values.
If you only need to check if a string can be converted, it is better to use the try/except
approach.
Checking for Floats with try-except
(Recommended)
The same try-except
pattern applies to checking for float convertibility:
def can_convert_to_float(string):
try:
float(string)
return True
except ValueError:
return False
print(can_convert_to_float('123')) # Output: True
print(can_convert_to_float('-123')) # Output: True
print(can_convert_to_float('3.14')) # Output: True
print(can_convert_to_float('1e-3')) # Output: True (scientific notation)
print(can_convert_to_float('abc')) # Output: False
- This correctly handles integers, negative numbers, decimals, and scientific notation. It's the most robust way to check for float convertibility.
Checking if a Float is a Whole Number
To check if a float
variable represents a whole number (e.g., 3.0
vs. 3.14
):
Using float.is_integer()
The is_integer()
method is the most direct and readable way:
print((3.00).is_integer()) # Output: True
print((3.14).is_integer()) # Output: False
Using the Modulo Operator (%
)
num = 5.00
result = num % 1 == 0
print(result) # Output: True
- The modulo operator returns the remainder of a division.
- If a number has no fractional parts the remainder after dividing by 1 will be 0.