Python 设置数据类型
设置数据类型
在 Python 中,当你为变量赋值时会设置数据类型:
例子 |
数据类型 |
试一试 |
x = "Hello World" |
str |
试一试 |
x = 20 |
int |
试一试 |
x = 20.5 |
float |
试一试 |
x = 1j |
complex |
试一试 |
x = ["apple", "banana", "cherry"] |
list |
试一试 |
x = ("apple", "banana", "cherry") |
tuple |
试一试 |
x = range(6) |
range |
试一试 |
x = {"name" : "Bill", "age" : 36} |
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(20) |
int |
试一试 |
x = float(20.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 |
试一试 |