0

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
sirisha
  • 73
  • 1
  • 8
  • 1
    Does this answer your question? [How can I check if a string represents an int, without using try/except?](https://stackoverflow.com/questions/1265665/how-can-i-check-if-a-string-represents-an-int-without-using-try-except) – Sayandip Dutta Feb 25 '21 at 11:57
  • 1
    Does this answer your question? [Checking if a string can be converted to float in Python](https://stackoverflow.com/questions/736043/checking-if-a-string-can-be-converted-to-float-in-python) – costaparas Feb 25 '21 at 12:10

4 Answers4

4

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.

Nastor
  • 638
  • 4
  • 15
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
1

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")
Nisarg Shah
  • 379
  • 1
  • 10
1

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!")
Adam Oellermann
  • 303
  • 1
  • 7