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,
ValueError
is 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 compile()
Python Program to Convert Decimal to Binary Using Recursion
Python Program to Transpose a Matrix
Python String rsplit()
Python String ljust()
Why String is Immutable in Java?
Python Program to Get a Substring of a String
Python Set union()
Python Machine Learning - Sebastian Raschka
Python if...else Statement
Python Program to Find the Size (Resolution) of a Image
Python Program to Sort Words in Alphabetic Order
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Make a Flattened List from Nested List
Java Program to Permute All Letters of an Input String
Python List insert()
CharSequence vs. String in Java
Python Statement, Indentation and Comments
Python ascii()
Python Set add()
Python staticmethod()
Convert String to Byte Array and Reverse in Java
Python String islower()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python input()
Python Program to Generate a Random Number
Converting a Stack Trace to a String in Java
Python abs()
Python Program to Convert Celsius To Fahrenheit
Python Program to Append to a File
Python Program to Compute all the Permutation of the String
Python range()