Python 数据类型
大约 2 分钟
Python 数据类型
内置数据类型
在编程中,数据类型是一个重要的概念。
变量可以存储不同类型的数据,不同类型的数据显示可以做不同的事情。
Python默认具有以下内置数据类型,分为以下几类:
| 文本类型: | str |
|---|---|
| 数字类型: | int, float, complex |
| 序列类型: | list, tuple, range |
| 映射类型: | dict |
| 设置类型: | set,frozenset |
| 布尔类型: | bool |
| 二进制类型: | bytes, bytearray, memoryview |
| 无类型: | NoneType |
获取数据类型
你可以通过使用 [type()] 函数来获取任何对象的数据类型:
示例
打印变量 x 的数据类型:
x = 5
print(type(x))
设置数据类型
在 Python 中,数据类型在您将值分配给变量时设置:
| Example | Data Type | Try it |
|---|---|---|
| x = "Hello World" | str | Try it » |
| x = 20 | int | Try it » |
| x = 20.5 | float | Try it » |
| x = 1j | complex | Try it » |
| x = ["apple", "banana", "cherry"] | list | Try it » |
| x = ("apple", "banana", "cherry") | tuple | Try it » |
| x = range(6) | range | Try it » |
| x = {"name" : "John", "age" : 36} | dict | Try it » |
| x = {"apple", "banana", "cherry"} | set | Try it » |
| x = frozenset({"apple", "banana", "cherry"}) | frozenset | Try it » |
| x = True | bool | Try it » |
| x = b"Hello" | bytes | Try it » |
| x = bytearray(5) | bytearray | Try it » |
| x = memoryview(bytes(5)) | memoryview | Try it » |
| x = None | NoneType | Try it » |
设置特定数据类型
如果您想指定数据类型,可以使用以下构造函数:
| Example | Data Type | Try it |
|---|---|---|
| x = str("Hello World") | str | Try it » |
| x = int(20) | int | Try it » |
| x = float(20.5) | float | Try it » |
| x = complex(1j) | complex | Try it » |
| x = list(("apple", "banana", "cherry")) | list | Try it » |
| x = tuple(("apple", "banana", "cherry")) | tuple | Try it » |
| x = range(6) | range | Try it » |
| x = dict(name="John", age=36) | dict | Try it » |
| x = set(("apple", "banana", "cherry")) | set | Try it » |
| x = frozenset(("apple", "banana", "cherry")) | frozenset | Try it » |
| x = bool(5) | bool | Try it » |
| x = bytes(5) | bytes | Try it » |
| x = bytearray(5) | bytearray | Try it » |
| x = memoryview(bytes(5)) | memoryview | Try it » |
