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
Learn Flask development and learn to build cool apps with our premium Python course on Udemy.