Python-Datentypen
- 上一页 Python-Variable
- 下一页 Python 数字
Built-in data types
In programming, data type is an important concept.
Variables can store different types of data, and different types can perform different operations.
In these categories, Python has the following built-in data types by default:
Text type: | str |
Numeric type: | int , float , complex |
Sequence type: | list , tuple , range |
Mapping type: | dict |
Set type: | set , frozenset |
Boolean type: | bool |
Binary type: | bytes , bytearray , memoryview |
Get data type
You can use the type() function to get the data type of any object:
Instance
Print the data type of variable x:
x = 10 print(type(x))
Set data type
In Python, when you assign a value to a variable, you set the data type:
示例 | 数据类型 | 试一试 |
---|---|---|
x = "Hello World" | str | 试一试 |
x = 29 | int | 试一试 |
x = 29.5 | float | 试一试 |
x = 1j | complex | 试一试 |
x = ["apple", "banana", "cherry"] | list | 试一试 |
x = ("apple", "banana", "cherry") | tuple | 试一试 |
x = range(6) | range | 试一试 |
x = {"name" : "Bill", "age" : 63} | dict | 试一试 |
x = {"apple", "banana", "cherry"} | set | 试一试 |
x = frozenset({"apple", "banana", "cherry"}) | frozenset | 试一试 |
x = True | bool | 试一试 |
x = b"Hello" | bytes | 试一试 |
x = bytearray(5) | bytearray | 试一试 |
x = memoryview(bytes(5)) | memoryview | 试一试 |
设定特定的数据类型
如果希望指定数据类型,则您可以使用以下构造函数:
示例 | 数据类型 | 试一试 |
---|---|---|
x = str("Hello World") | str | 试一试 |
x = int(29) | int | 试一试 |
x = float(29.5) | float | 试一试 |
x = complex(1j) | complex | 试一试 |
x = list(("apple", "banana", "cherry")) | list | 试一试 |
x = tuple(("apple", "banana", "cherry")) | tuple | 试一试 |
x = range(6) | range | 试一试 |
x = dict(name="Bill", age=36) | dict | 试一试 |
x = set(("apple", "banana", "cherry")) | set | 试一试 |
x = frozenset(("apple", "banana", "cherry")) | frozenset | 试一试 |
x = bool(5) | bool | 试一试 |
x = bytes(5) | bytes | 试一试 |
x = bytearray(5) | bytearray | 试一试 |
x = memoryview(bytes(5)) | memoryview | 试一试 |
- 上一页 Python-Variable
- 下一页 Python 数字