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 max()
Python @property decorator
Python Program to Check Whether a String is Palindrome or Not
Python Statement, Indentation and Comments
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python setattr()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Python Shallow Copy and Deep Copy
Python Multiple Inheritance
Python Program to Find the Largest Among Three Numbers
Python Objects and Classes
Python String capitalize()
Check if a String is a Palindrome in Java
Python Dictionary update()
Python Data Types
How to Remove the Last Character of a String?
Python frozenset()
Python delattr()
Machine Learning with Python for everyone - Mark E.Fenner
Python sorted()
Java – Random Long, Float, Integer and Double
Python String rstrip()
Python Program to Make a Flattened List from Nested List
Converting String to Stream of chars
Python bytes()
Python input()
How to get current date and time in Python?
Python Exception Handling Using try, except and finally statement
Python Modules
Python Program to Get the Class Name of an Instance
Python Inheritance
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty