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 Closures
Python Program to Print Colored Text to the Terminal
Python Set issubset()
Split a String in Java
Python String translate()
Python Program to Display Powers of 2 Using Anonymous Function
Python sum()
Python Custom Exceptions
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python String replace()
Python Sets
Python String rpartition()
Python Program to Print the Fibonacci sequence
Python Program to Print Output Without a Newline
Python globals()
Python Errors and Built-in Exceptions
Python String isprintable()
Python iter()
Java – Generate Random String
Map to String Conversion in Java
Python Input, Output and Import
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python String ljust()
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Generate a Random Number
Python staticmethod()
Python Function Arguments
Python Program to Safely Create a Nested Directory
Python Program to Check Armstrong Number
Python super()
Python Program to Concatenate Two Lists
Python Program to Create a Countdown Timer