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 Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Machine Learning - Sebastian Raschka
Python String isupper()
Python Program to Count the Occurrence of an Item in a List
Node.js vs Python for Backend Development
Python any()
Python Program to Calculate the Area of a Triangle
Python Program to Safely Create a Nested Directory
Python Program to Check Prime Number
Python Decorators
Python Set union()
Python Program to Print the Fibonacci sequence
Python len()
Python String startswith()
Python List copy()
Python Operators
Python repr()
Python bytes()
Python Program to Find Sum of Natural Numbers Using Recursion
Python String count()
Python Namespace and Scope
Python Set copy()
Python Program to Convert Kilometers to Miles
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python getattr()
Python Program to Differentiate Between del, remove, and pop on a List
Python while Loop
Python divmod()
Python complex()
Python Program to Shuffle Deck of Cards
Python ascii()
Debug a JavaMail Program