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,
ValueError
is 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:
String Processing with Apache Commons Lang 3
Python List count()
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Inheritance
Split a String in Java
Python pow()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python Program to Transpose a Matrix
Python RegEx
Python Program to Iterate Over Dictionaries Using for Loop
Python Set update()
Python Program to Compute all the Permutation of the String
Python String format()
Debug a JavaMail Program
Python zip()
Python staticmethod()
Python Machine Learning Eqution Reference - Sebastian Raschka
Convert String to Byte Array and Reverse in Java
Python Program to Split a List Into Evenly Sized Chunks
Python Closures
Python Program to Print Output Without a Newline
Python Program to Check If Two Strings are Anagram
Python List insert()
Python dir()
Python Errors and Built-in Exceptions
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python Program to Find LCM
Python timestamp to datetime and vice-versa
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python Anonymous / Lambda Function
Python String rpartition()
Python Program to Find the Size (Resolution) of a Image