How To Check If A String Is An Integer Or A Float In Python

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

To check if a string is an integer or a float in Python, we can use methods to check digits in Python, like the isnumeric() and isdigit() methods. Please read the following article for details.

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

Use the str.isnumeric() method and the float() function

Syntax of the str.isnumeric() method:

str.isnumeric()

The isnumeric() method returns True if the string contains only numeric characters, otherwise returns.

Syntax of the float() function:

float([x])

Example:

  • Customize a function. Use the isnumeric() method to check if the function’s argument is an integer. If the function returns False(else statement), output the string command as a float. 
def checkString(num):
    if num.isnumeric() is True:
        print('String is an Integer')
    else:
        float(num)
        print('String is a Float')

# Call checkString function to check if a string is an Integer or a Float
checkString('2')
checkString('2.3')

Output:

String is an Integer
String is a Float

In the above example, I call the function ‘checkString’ and pass it two arguments with values ​​’2′ and ‘2.3’. The isnumeric() method checks those two arguments and finds that ‘2’ contains only numeric characters, so print the statement ‘string is an integer (execute the command correctly) with the value ‘2.3’, then execute the command else (the isnumeric() method returns False).

Use the string.isdigit() method

Syntax:

string.isdigit()

The string.isdigit() method:

  • Returns True if the string contains all numbers.
  • Returns False if the string contains more than one non-numeric character.

Example:

  • Customize a function. Use the isdigit() method to check if the function’s argument is an integer. If the function returns False(else statement), output the string command as a float. 
def checkString(num):
    if num.isdigit() is True:
        print('String is an Integer')
    else:
        float(num)
        print('String is a Float')

# Call checkString function to check if a string is an Integer or a Float
checkString('2')
checkString('2.3')

Output:

String is an Integer
String is a Float

In the above example, I call the function ‘checkString’ and pass it two arguments with values ​​’2′ and ‘2.3’. The isdigit() method checks those two arguments and finds that ‘2’ contains only numeric characters, so print the statement ‘string is an integer (execute the command correctly) with the value ‘2.3’ then execute the command else (the isdigit() method returns False).

Summary

Those are two ways to check if a string is an integer or a float in Python. Both use the alphanumeric checking methods in Python. You can use it whichever way you like. If there is a better way, please comment below. We appreciate it.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *