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


当前回答

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'>

其他回答

print type(variable_name)

在处理此类问题时,我也强烈建议使用IPython交互式解释器。它允许您键入variable_name?并将返回关于对象的完整信息列表,包括类型和类型的文档字符串。

e.g.

In [9]: var = 123

In [10]: var?
Type:       int
Base Class: <type 'int'>
String Form:    123
Namespace:  Interactive
Docstring:
    int(x[, base]) -> integer

如果可能,将字符串或数字转换为整数。浮点参数将被截断为零(这不包括字符串浮点数的表示!)转换字符串时,请使用可选的基数。在转换非字符串。如果参数超出整数范围,则为长对象将返回。

你的意思是用Python还是用ctypes?

在第一种情况下,您根本不可能——因为Python没有带符号/无符号的16/32位整数。

在第二种情况下,可以使用type():

>>> import ctypes
>>> a = ctypes.c_uint() # unsigned int
>>> type(a)
<class 'ctypes.c_ulong'>

有关ctypes及其类型的更多参考信息,请参阅官方文档。

对于python2.x,请使用

print type(variable_name)

对于python3.x,请使用

print(type(variable_name))

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

这很简单。你这样做。

print(type(variable_name))