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 Convert Two Lists Into a Dictionary
Python String expandtabs()
Python List index()
Node.js vs Python for Backend Development
Python Program to Compute the Power of a Number
Python Tuple
Python String rsplit()
Encode a String to UTF-8 in Java
Case-Insensitive String Matching in Java
Python Data Structures and Algorithms - Benjamin Baka
Python List reverse()
Python Set intersection()
Python Program to Find All File with .txt Extension Present Inside a Directory
Python Set issubset()
Python Keywords and Identifiers
Python vars()
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Reverse a Number
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Python callable()
Python Program to Multiply Two Matrices
Python Inheritance
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Display the multiplication Table
Deep Learning with Python - Francois Cholletf
Python memoryview()
Python Set issuperset()
Python String islower()
Python set()
Python Program to Check if a Number is Odd or Even
Python Program to Count the Number of Each Vowel
Python Set difference()