1

I want to check the type of input on the screen by using

python types module

I have used the type(2) is int for integer. ---->>>working I have used the type("Vivek") is str for string. ---->>>working but i am confused when I take input using raw_input()

import types

p = raw_input("Enter input ")

if I entered string like "vivek" on console then it is ok

the matter is when int and float entered

so what will be the canonical way to checked whether an input is of boolean,int,char,string,long,byte,double in python.

MKB
  • 777
  • 1
  • 9
  • 27
avk avk
  • 56
  • 4

1 Answers1

2

It up to you to convert your input to whatever you need.

But, you can guess like this:

import sys

p = raw_input("Enter input")

if p.lower() in ("true", "yes", "t", "y"):
    p = True
elif p.lower() in ("false", "no", "f", "n"):
    p = False
else:
    try:
        p = int(p)
    except ValueError:
        try:
            p = float(p)
        except ValueError:
            p = p.decode(sys.getfilesystemencoding()

This support bool, int, float and unicode.

Notes:

  • Python has no char type: use a string of length 1,
  • This int function can parse int values but also long values and even very long values,
  • The float type in Python has a precision of a double (which doesn't exist in Python).

See also: Parse String to Float or Int

Community
  • 1
  • 1
Laurent LAPORTE
  • 21,958
  • 6
  • 58
  • 103