如何查看变量的类型?(例如无符号32位)


当前回答

Python中的简单类型检查示例:

assert type(variable_name) == int

assert type(variable_name) == bool

assert type(variable_name) == list

其他回答

Python没有您所描述的类型。有两种类型用于表示整数值:int,它对应于C中平台的int类型;long,它是一个任意精度的整数(即,它根据需要增长,没有上限)。如果表达式产生的结果无法存储在int中,则int将被无声地转换为long。

使用type()内置函数:

>>> i = 123
>>> type(i)
<type 'int'>
>>> type(i) is int
True
>>> i = 123.456
>>> type(i)
<type 'float'>
>>> type(i) is float
True

要检查变量是否为给定类型,请使用isinstance:

>>> i = 123
>>> isinstance(i, int)
True
>>> isinstance(i, (float, str, set, dict))
False

请注意,Python没有与C/C++相同的类型,这似乎是您的问题。

这取决于你的意思。在Python2.x中,由于历史原因,有两种整数类型,int(限制为sys.maxint)和long(无限精度)。在Python代码中,这不会有什么区别,因为当数字太大时,解释器会自动转换为long。如果您想了解底层解释器中使用的实际数据类型,这取决于实现。(CPython位于Objects/intobject.c和Objects/longobject.c中)要了解系统类型,请查看使用结构模块的cdleary答案。

这很简单。你这样做。

print(type(variable_name))

python中有许多数据类型,如:

Text Type:  str
Numeric Types:  int, float, complex
Sequence Types: list, tuple, range
Mapping Type:   dict
Set Types:  set, frozenset
Boolean Type:   bool
Binary Types:   bytes, bytearray, memoryview
None Type:  NoneType

在这里,我写了一个代码,其中有一个包含所有类型数据类型的列表示例,并打印它们的类型

L = [
    "Hello World",
    20,
    20.5,
    1j,
    ["apple", "banana", "cherry"],
    ("apple", "banana", "cherry"),
    range(6),
    {"name" : "John", "age" : 36},
    {"apple", "banana", "cherry"},
    frozenset({"apple", "banana", "cherry"}),
    True,
    b"Hello",
    bytearray(5),
    memoryview(bytes(5)),
    None
]
for _ in range(len(L)):
    print(type(L[_]))

输出:

<class 'str'>
<class 'int'>
<class 'float'>
<class 'complex'>
<class 'list'>
<class 'tuple'>
<class 'range'>
<class 'dict'>
<class 'set'>
<class 'frozenset'>
<class 'bool'>
<class 'bytes'>
<class 'bytearray'>
<class 'memoryview'>
<class 'NoneType'>