In this example, you will learn to check if a string is a number (float).
To understand this example, you should have the knowledge of the following Python programming topics:
Using float()
def isfloat(num):
try:
float(num)
return True
except ValueError:
return False
print(isfloat('s12'))
print(isfloat('1.123'))
Output
False True
Here, we have used try except in order to handle the ValueError if the string is not a float.
- In the function
isfloat(),float()tries to convert num to float. If it is successful, then the function returnsTrue. - Else,
ValueErroris raised and returnsFalse.
For example, 's12' is alphanumeric, so it cannot be converted to float and False is returned; whereas, '1.123' is a numeric, so it is successfully converted to float.
Related posts:
Python String find()
Python Dictionary
Python Modules
Python for Loop
Python Set intersection()
Python Program to Get the Full Path of the Current Working Directory
Python Program to Create a Countdown Timer
Python round()
Java String to InputStream
Python dir()
Python Program to Get the File Name From the File Path
Python print()
Python Program to Safely Create a Nested Directory
Python String rfind()
Python Namespace and Scope
Python Dictionary values()
Python Program to Get the Last Element of the List
Python Set copy()
Python chr()
Python setattr()
Python property()
Python isinstance()
Python hash()
Python Program to Iterate Through Two Lists in Parallel
Python String isnumeric()
Python Program to Find the Square Root
Python Program to Find Factorial of Number Using Recursion
Python String format()
Python Program to Find the Factors of a Number
Python set()
Python Get Current time
Python Operators