如何在Python中确定文字的类型?

时间:2018-02-22 16:37:41

标签: python ruby types literals

在Ruby中,您可以使用.class来确定文字的类型。例如:

   100.class 
=> Fixnum
   "Hi".class
=> String
   3.14.class
=> Float
   [1, 2, 3].class
=> Array
   {:name => "John"}.class
=> Hash

我怎样才能在Python中做同样的事情?我知道什么是文字和Python文字语法。我只是想知道我是否有办法确定它。提前谢谢。

3 个答案:

答案 0 :(得分:3)

使用type()

>>> type(2)
<class 'int'>
>>> type(2.2)
<class 'float'>
>>> type(100)
<class 'int'>
>>> type("hi")
<class 'str'>
>>> type(3.14)
<class 'float'>
>>> type([1,2,3])
<class 'list'>
>>> type({'a': 1})
<class 'dict'>

答案 1 :(得分:2)

您可以使用if type(a) == int: do_something() ,如前所述 - 但此功能仅供检查之用,主要用于repl / shell / console等。

我的意思是,写这样的东西,

isinstance(variable, class_name)

不是pythonic。

出于这种目的,使用{{1}}更加pythonic,更有意义。我使用有意义,因为作为基于对象的语言,python没有类型,至少你应该假装它没有类型。您创建或创建的每个对象都是您创建的过程的输出,是某些类的实例 - 至少您应该以这种方式接近python。

答案 2 :(得分:1)

使用type(expression)确定表达式的类型