Search code examples
pythonstringisinstance

Is there any way to find whether a value in string is a float or not in python?


I have a problem with string, I am aware that using isdigit() we can find whether an integer in the string is an int or not but how to find when its float in the string. I have also used isinstance() though it didn't work. Any other alternative for finding a value in the string is float or not??

My code:

v = '23.90'
isinstance(v, float)

which gives:

False

Excepted output:

True

Solution

  • You could just cast it to float or int, and then catch an eventual exception like this:

    try:
        int(val)
    except:
        print("Value is not an integer.")
    try:
        float(val)
    except:
        print("Value is not a float.")
    

    You can return False in your except part and True after the cast in the try part, if that's what you want.