基本数据类型
- Number(数字)
- String(字符串)
- bool(布尔类型)
- List(列表): 类似 JS 中的数组
- Tuple(元组)
- Set(集合)
- Dictionary(字典): 类似 JS 中的对象(k=v)
python
age = 10 # Number
name = "tom" # String
isBoy = True # Boolean
friends = [ # List
"jerry",
"alex",
]
info = { # dictionary
"firstName": "John",
"lastName": "Doe",
"age": 28,
}
获取变量类型
type
方法返回的是变量类型字符串
python
age = 10 # Number
name = "tom" # String
isBoy = True # Boolean
friends = [ # List
"jerry",
"alex",
]
info = { # dictionary
"firstName": "John",
"lastName": "Doe",
"age": 28,
}
print(type(age))
print(type(name))
print(type(isBoy))
print(type(info))
判断数据类型
isinstance
方法可以判断某个数据是否是某个类型, 返回一个 Boolean 值
python
print(isinstance("hello", str)) # True
print(isinstance(11, str)) # False
数据类型转换
- int(x)
- float(x)
- str(x)
python
# 数字转字符串
print(str(10)) # "10"
# 数字(浮点数)转字符串
print(str(10.11)) # "10.11"
# 字符串转数字
print(int("101")) # 101
# 字符串转数字(浮点数)
print(float("10.1")) # 10.1
# 浮点数转整数(丢失精度:丢失小数点后面的值)
print(int(10.11)) # 10