sirisha
sirisha

Reputation: 73

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

Upvotes: 0

Views: 158

Answers (4)

Nisarg Shah
Nisarg Shah

Reputation: 389

You can check whether the number is integer or not by isdigit(), and depending on that you can return the value.

s = '23'

try:
    if s.isdigit():
        x = int(s)
        print("s is a integer")
    else:
        x = float(s)
        print("s is a float")
except:
    print("Not a number or float")

Upvotes: 1

Adam Oellermann
Adam Oellermann

Reputation: 303

A really simple way would be to convert it to float, then back to string again, and then compare it to the original string - something like this:

v = '23.90'
try:
    if v.rstrip('0') == str(float(v)).rstrip('0'):
        print("Float")
    else:
        print("Not Float")
except:
    print("Not Float!")

Upvotes: 1

Maybe you can try this

def in_float_form(inp):
   can_be_int = None
   can_be_float = None
   try:
      float(inp)
   except:
      can_be_float = False
   else:
      can_be_float = True
   try:
      int(inp)
   except:
      can_be_int = False
   else:
      can_be_int = True
   return can_be_float and not can_be_int
In [4]: in_float_form('23')
Out[4]: False

In [5]: in_float_form('23.4')
Out[5]: True

Upvotes: 1

Nastor
Nastor

Reputation: 638

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.

Upvotes: 4

Related Questions