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,
ValueErroris 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 String isnumeric()
Python iter()
Python Program to Create Pyramid Patterns
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Program to Multiply Two Matrices
Python Program to Get the Last Element of the List
Python Set isdisjoint()
Python ord()
Python Modules
Python Program to Represent enum
Count Occurrences of a Char in a String
Adding a Newline Character to a String in Java
Python String count()
Python String strip()
Python String istitle()
Python tuple()
Python RegEx
Python Program Read a File Line by Line Into a List
Python Program to Randomly Select an Element From the List
Python Program to Find Sum of Natural Numbers Using Recursion
Python Statement, Indentation and Comments
Python String ljust()
Python sorted()
Python String rjust()
Python Strings
Python Global, Local and Nonlocal variables
Python complex()
Python List remove()
Python Closures
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Dictionary copy()
Debug a JavaMail Program