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 super()
Python Dictionary pop()
Python oct()
Python timestamp to datetime and vice-versa
Python Set copy()
Python eval()
Python String partition()
String Hashing
Python Program to Get Line Count of a File
Python set()
Python Set remove()
Python Program to Copy a File
Python memoryview()
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python String isalnum()
Python Dictionary clear()
Python String rindex()
String Set Queries
Python globals()
Python Namespace and Scope
Python Program to Iterate Over Dictionaries Using for Loop
Python Set add()
Python Program to Sort Words in Alphabetic Order
Python Multiple Inheritance
Python Program to Count the Number of Each Vowel
Python hasattr()
Python List clear()
Python String find()
Python Program to Get the Full Path of the Current Working Directory
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Objects and Classes
Java InputStream to String