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
2

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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!")

Comments

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")

2 Comments

What if s = "text" ?
@Ruan This try, expect block will handle the edge case of s = "text".

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.