def is_float(string): try: float(string) return True except ValueError: return False print(is_float('1.23')) print(is_float('123')) print(is_float('1.23a'))
True
True
False
To check if a string is a number (float) in python, you can use isnumeric() in combination with the replace() method to check if the string can be casted to float or not.
Another way to check if a string can be casted to float is using the str.replace() function in combination with str.isnumeric():
def is_float(string): if string.replace(".", "").isnumeric(): return True else: return False print(is_float('1.23')) # True print(is_float('123')) # True print(is_float('1.23a')) # False
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.