在python中有如下数据类型
文本类型: | str |
数值类型: | int, float, complex |
序列类型: | list, tuple, range |
映射类型: | dict |
集合类型: | set, frozenset |
布尔类型: | bool |
二进制类型: | bytes, bytearray, memoryview |
type()函数
如果你不知道你所定义或者输入的数据是什么类型就可以用函数type()来获取
a = 10
print(type(a))
'int'
a = 10.0
print(type(a))
'float'
a = yyw
print(type(a))
'str'
设置数据类型
x = "Hello World" | str |
x = 1 | int |
x = 1.0 | float |
x = 1j | complex |
x = ["apple", "banana",] | list |
x = ("apple", "banana") | 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(1) | int |
x = float(1.0) | float |
x = complex(1j) | complex |
x = list(("apple", "banana")) | list |
x = tuple(("apple", "banana")) | tuple |
x = range(6) | range |
x = dict(name="Bill", age=18) | dict |
x = set(("apple", "banana", "cherry")) | set |
x = frozenset(("apple", "banana")) | frozenset |
x = bool(5) | bool |
x = bytes(5) | bytes |
x = bytearray(5) | bytearray |
x = memoryview(bytes(5)) | memoryview |
指定变量类型。
- int() - 用整数字面量、浮点字面量构造整数(通过对数进行下舍入),或者用表示完整数字的字符串字面量
- float() - 用整数字面量、浮点字面量,或字符串字面量构造浮点数(提供表示浮点数或整数的字符串)
- str() - 用各种数据类型构造字符串,包括字符串,整数字面量和浮点字面
x = float(1) # x 将是 1.0
y = float(2.5) # y 将是 2.5
z = float("3") # z 将是 3.0
w = float("4.6") # w 将是 4.6
x = str("S2") # x 将是 'S2'
y = str(3) # y 将是 '3'
z = str(4.0) # z 将是 '4.0'
x = int(1) # x 将是 1
y = int(2.5) # y 将是 2
z = int("3") # z 将是 3