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 tuple()
Python String lower()
Python Program to Find ASCII Value of Character
Python List
Python Program to Find Armstrong Number in an Interval
Python String count()
Python Program to Check Armstrong Number
Python Program to Access Index of a List Using for Loop
Python Program to Create Pyramid Patterns
Python float()
Python String rindex()
Python Decorators
Python List copy()
Python Program to Sort Words in Alphabetic Order
Python Program to Check If Two Strings are Anagram
Python Program to Concatenate Two Lists
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python chr()
Python object()
Python Program to Get the File Name From the File Path
Python any()
Python Program to Convert Celsius To Fahrenheit
Python Set union()
Python String replace()
Python Operator Overloading
Java String Conversions
Python for Loop
Python Program to Multiply Two Matrices
Python ord()
Python property()
Python repr()
Python compile()