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 sum()
Python Set issubset()
Python open()
Python Program to Capitalize the First Character of a String
Python len()
Java – String to Reader
Python String capitalize()
Python issubclass()
Python String rsplit()
Python Functions
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Set intersection()
Java String to InputStream
Python String upper()
Python Program to Find the Sum of Natural Numbers
Python Set symmetric_difference_update()
How to Remove the Last Character of a String?
Python break and continue
Python Get Current time
Python bin()
Python eval()
Python setattr()
Jackson – Marshall String to JsonNode
Python Program to Find Hash of File
Generate a String
Python max()
Python Program to Split a List Into Evenly Sized Chunks
Python Machine Learning - Sebastian Raschka
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Check Prime Number
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
String Initialization in Java