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 setattr()
Python bytearray()
Python String expandtabs()
Python Input, Output and Import
Python String casefold()
Python exec()
Python String isupper()
Python hex()
Python List count()
Python List index()
Python Modules
Python Set difference()
Python Operators
Python repr()
Python Program to Safely Create a Nested Directory
Python Dictionary popitem()
Python Get Current time
Python __import__()
Python @property decorator
Python min()
Python Set copy()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Package
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Set isdisjoint()
Split a String in Java
Python Program to Count the Number of Occurrence of a Character in String
Python frozenset()
Python complex()
Python all()
Python Shallow Copy and Deep Copy