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 Shallow Copy and Deep Copy
Python type()
Python sum()
Python print()
Python Program to Find LCM
Python Program to Reverse a Number
Machine Learning with Python for everyone - Mark E.Fenner
Python String islower()
Python RegEx
Python Function Arguments
Python Program to Count the Number of Digits Present In a Number
Python String lower()
Python Modules
Python String encode()
Python Program to Display the multiplication Table
Python chr()
Python bin()
Python Set discard()
Python Input, Output and Import
Check If a String Is Numeric in Java
Python format()
Python Program to Remove Duplicate Element From a List
Python Program to Remove Punctuations From a String
Python List pop()
Python String rjust()
Intelligent Projects Using Python - Santanu Pattanayak
Python min()
Python Objects and Classes
Python Program to Check if a Key is Already Present in a Dictionary
Java InputStream to String
Python List count()
Python String title()