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 Program to Find Numbers Divisible by Another Number
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Convert String to Byte Array and Reverse in Java
Python Program Read a File Line by Line Into a List
Python RegEx
APIs in Node.js vs Python - A Comparison
Python range()
Python Program to Create Pyramid Patterns
Python String replace()
Python ascii()
Python Variables, Constants and Literals
Python Program to Find ASCII Value of Character
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Program to Generate a Random Number
Number Formatting in Java
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python Program to Shuffle Deck of Cards
Python String rstrip()
Java – Reader to String
Python Program to Sort Words in Alphabetic Order
Python Program to Split a List Into Evenly Sized Chunks
Python sum()
Python Program to Find the Sum of Natural Numbers
Python Tuple
Python String rfind()
Python Set discard()
Python String upper()
Python list()
Python String isalpha()
Python Decorators
Python String splitlines()
Python Function Arguments