【问题标题】:what is the canonical way to check the type of input? [duplicate]检查输入类型的规范方法是什么? [复制]
【发布时间】:2017-01-22 03:53:42
【问题描述】:

我想使用

检查屏幕上的输入类型

pythontypes 模块

我使用type(2) is int 表示整数。 ---->>>工作 我已将type("Vivek") is str 用于字符串。 ---->>>工作 但是当我使用raw_input()接受输入时我很困惑

import types

p = raw_input("Enter input ")

如果我在console 上输入了类似“vivek”的字符串 那么就可以了

问题在于intfloat 何时输入

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

【问题讨论】:

  • 使用raw_input,你总是会得到一个str类型的字节字符串(使用Python 2)。
  • 而您在 python3 中使用input() 阅读的所有内容都是str 类型
  • 对了,Python中没有char类型,或者byte,或者double...
  • @MKB 我不同意。 OP 要求在 Python 中进行字符串转换。这个问题有点尴尬。

标签: python python-2.7 python-3.x


【解决方案1】:

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

但是,你可以这样猜测:

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 中不存在)。

另请参阅:Parse String to Float or Int

【讨论】:

  • ("true", "yes", "t", "y"): 我没明白 t y 的意思
  • @avkavk:这是人类可读的英文真值示例:“t”表示“true”,“y”表示“yes”。您可以使用自己的字符串。
猜你喜欢
  • 2010-09-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-09-27
  • 1970-01-01
  • 2014-10-03
  • 2015-12-26
  • 2011-10-05
相关资源
最近更新 更多