检查输入类型的规范方法是什么? [英] what is the canonical way to check the type of input?

查看:31
本文介绍了检查输入类型的规范方法是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过使用

python types 模块

我使用 type(2) is int 表示整数.---->>>工作我使用 type("Vivek") is str 作为字符串.---->>>工作但是当我使用 raw_input()

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

如果我在控制台上输入了像vivek"这样的字符串那么就可以了

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

问题是intfloat输入时

那么检查输入是否为 boolean,int,char,string,long 的规范方法是什么,byte,double in python.

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

推荐答案

您可以将输入转换为您需要的任何内容.

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

但是,你可以这样猜:

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

支持boolintfloatunicode.

注意事项:

  • Python 没有 char 类型:使用长度为 1 的字符串,
  • 这个 int 函数可以解析 int 值,也可以解析 long 值,甚至很长的值,
  • Python 中的 float 类型具有 double 的精度(Python 中不存在).
  • 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).

另见:将字符串解析为浮点数或整数

这篇关于检查输入类型的规范方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆