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 zfill()
Python Program to Generate a Random Number
Python Package
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program Read a File Line by Line Into a List
Python Operator Overloading
Python repr()
String Set Queries
Debug a JavaMail Program
Deep Learning with Python - Francois Cholletf
Python Dictionary clear()
Python Dictionary fromkeys()
Check if a String is a Palindrome in Java
Python vars()
Python Program to Safely Create a Nested Directory
Python enumerate()
Intelligent Projects Using Python - Santanu Pattanayak
Python next()
Deep Learning in Python - LazyProgrammer
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python String isalnum()
Python delattr()
Python String rfind()
Reading an HTTP Response Body as a String in Java
Python List count()
Python String upper()
Java Program to Permute All Letters of an Input String
Python Keywords and Identifiers
Python Tuple
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Check if a Number is Odd or Even
Python String maketrans()