Check if a string is an Integer or a Float in Python

avatar

Borislav Hadzhiev

Last updated: Jul 13, 2022

banner

Photo from Unsplash

Check if a string is an Integer or a Float in Python #

To check if a string is an integer or a float:

  1. Use the str.isdigit() method to check if every character in the string is a digit.
  2. If the method returns True, the string is an integer.
  3. If the method returns False, the string is a floating-point number.
main.py
my_str = '2468' if my_str.isdigit(): my_num = int(my_str) print('String is an integer') else: my_num = float(my_str) print('String is a float') print(my_num) # 👉️ 2468
If you have to handle negative numbers, scroll down to the try/except solution.

We used the str.isdigit() method to check if all characters in the string are digits.

The str.isdigit method returns True if all characters in the string are digits and there is at least 1 character, otherwise False is returned.

The str.isdigit() metho would return False if the string has a decimal point or starts with a minus - (is a negative number).

main.py
print('-123'.isdigit()) # 👉️ False print('1.23'.isdigit()) # 👉️ False

If you don't have to handle negative numbers, using the str.isdigit() method should be sufficient.

If you have to handle negative numbers, use a try/except block.

To check if a string is an integer or a float:

  1. Wrap the call to the int() class in a try block.
  2. If the call to the int() class succeeds, the string is an integer.
  3. If the except block runs, the string is a floating-point number.
main.py
my_str = '-2468' try: my_num = int(my_str) # 👇️ this runs print('String is an integer') except ValueError: my_num = float(my_str) print('String is a float') print(my_num) # 👉️ -2468

We used a try/except statement to check if a string is an integer or a float.

If the try block runs successfully, the string is an integer.

If calling the int() class with the string raises a ValueError, the except block is run and the string is a floating-point number.

Unlike the str.isdigit() method, this approach also handles negative numbers.

Using a try/except statement in this manner is commonly known as "asking for forgiveness rather than permission".

We pass the string to the int() class not knowing whether the conversion will be successful, and if a ValueError error is raised, we handle it in the except block.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.