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 Dictionary items()
Python Iterators
Java – Generate Random String
CharSequence vs. String in Java
Python int()
Python String isalpha()
Python dict()
Python Program to Convert Kilometers to Miles
Python bytes()
Python Program to Generate a Random Number
How to Get Started With Python?
Python Program to Make a Simple Calculator
Python Program to Check Leap Year
Python complex()
Python hash()
Python Program to Print Output Without a Newline
Python Program to Print Colored Text to the Terminal
Python delattr()
Python round()
Python String maketrans()
Python String isnumeric()
Python max()
Array to String Conversions
Python enumerate()
Python format()
Python next()
Case-Insensitive String Matching in Java
Python set()
Python Set add()
Reading an HTTP Response Body as a String in Java
JavaScript Methods of RegExp and String
Python Program to Return Multiple Values From a Function