How to check if a string is int or float in Python?

How to check if a string is int or float in Python?

In Python, we have to check whether a string can be a number before we can perform any operations that involve mathematics because it makes sure that no errors can be raised while processing the input data. In this blog, we will learn different ways to check whether a string represents a number, either an integer or a float, in Python with examples for each.

Table of Contents:

Methods to Check If a String is an int or float in Python

Here are some methods you can use to check if a string is a number in Python:

Method 1: Using isdigit() method in Python

The isdigit() method gives a fast way to check whether a string represents a number. The only limitation is it does not work for decimal values and negative numbers.

Example:

Python

Output:

Explanation: The isdigit() method returns true when all characters in the string are numbers. Any sort of negative or decimal number is not supported by this method.

Method 2: Using the try-except block in Python

This try-except block will convert the string into a number and check whether the string is a number. It works well with both integers and floats.

Example:

Python

Output:

Explanation: The method converts a string into a float/int number in the try-except block. If the string fails the conversion, a Value Error is raised stating that this string is not a number.

Method 3: Using Regular Expressions in Python

Regular expression(Regex) matches the patterns for numbers, counting from decimals, negatives, and integers.

Example:

Python

Output:

Explanation: The regex pattern ^-?\d+(\.\d+)?$ matches integers and floats (both positive and negative). It handles decimal points and negative numbers as well.

Method 4: Using float() and int() function in Python

The string can be converted into a float or int number in Python by using the float/int function and, after it’s converted, check whether you are getting conversion errors or not.

Example:

Python

Output:

Explanation: Here float() and int() are used which are similar to try-except but you can use float() to handle integers with decimals.

Method 5: Using isnumeric() Method in Python

The isnumeric() method checks whether all the characters in the string are numeric and returns True only if the condition is satisfied. This method identifies numbers from other languages as well but does not work for negative numbers.

Example:

Python

Output:

Explanation: Here, the isnumeric() method returns the ‘String is numeric’ if the string defines is valid number by checking the numbers in different languages, like Arabic and Roman numerals.

Method 6: Without Using any Built-in Methods

We can check if the string represents a number by manually looping over each character. This method works well for decimal values but not negative.

Example:

Python

Output:

Explanation: Here, it is checked if a string represents a valid number by allowing digits and only one decimal point. It returns True for the examples that satisfy the condition else returns False.

Performance Comparison of Different Methods

  1. isdigit(): This is a fast method when it comes to checking for a numeric query, but it works only for positive integers.
  2. try-except with float(): This method is more efficient and flexible since it handles integers, floats, and negatives quite well.
  3. Regular Expressions (re.match): Regex is slower than the try-except but useful for checking the numeric formats.
  4. float() and int() functions: The float() and int() functions work similarly to try-except and give high performance when both checking and conversion of the strings are needed.
  5. isnumeric(): It is a method with limits because it doesn’t handle decimals or negatives, but has a high-performance level.

Best Practices to Check if a String is a Number in Python

  1. Always make sure you check for empty input before validation.
  2. The isdigit() does not support decimals or negative numbers, thus use it only for positive integers.
  3. Always use try-except with float() as it handles integers, floats, and negatives efficiently.
  4. Use regular expressions (re.match) for strict format checking when specific number formats are required.
  5. To improve the reusability and keep the code clean use the functions.
  6. To avoid errors caused by leading or trailing spaces use s.strip().

Conclusion

Python provides multiple methods to check if a string represents a number. The isdigit() method is useful for integers, but for more complex numbers, try-except can be used. Understanding these methods helps you effectively check if a string represents a number and prevent runtime errors.

FAQs

1. Can isdigit() handle negative numbers or decimals?

No, isdigit() cannot handle negative numbers or decimals. It only works with positive integers.

2. How can I check if a string represents a float in Python?

You can use a try-except block to convert the string to a float.

3. Is there a built-in Python method to check if a string is a number?

Python does not have a single built-in method to check if a string is a number.

4. Why is it important to check if a string represents a number before performing mathematical operations?

Checking before performing mathematical operations is important because it ensures whether the string can be a number, which prevents runtime errors during execution.

5. Are regular expressions (re.match) better than try-except?

Yes, regular expressions are better than try-except because they provide us with strict formatting but are generally slower.

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration. 

Full Stack Developer Course Banner