数据类型转换
int()
将其他有效的数据转为整数
取整
从字符串中解析整数
>>> int(3.14) # 将小数进行取整操作
3
>>> int("123") # 将数字字符串进行解析(默认十进制),解析出一个整数
123
>>> int("123abc")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '123abc'
>>> int("AD", 16) # 将数字字符串进行十六进制解析,结果都是十进制
173
# 10*16^1 + 13*16^0 = 173
>>> int("91A", 12)
1318
>>> 10 * 12 ** 0 + 1 * 12 ** 1 + 9 * 12 ** 2
1318
>>> int("A1F", 13)
Traceback (most recent call last):File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 13: 'A1F'
>>> int("91a", 100)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: int() base must be >= 2 and <= 36, or 0
base 进制基数 = [2, 36]
>>> int("98*!",12) # 出现特殊符号
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 12: '98*!'
>>> int("10010101") # 注意坑 二进制串特不一定是二进制数字
10010101
>>> int("10010101", 2)
149
float():
将其他的数据转为小数
>>> float(3)
3.0
>>> float(3.14)
3.14
>>> float("3.14")
3.14
>>> float("3.14", 10)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: float expected at most 1 argument, got 2
str():
将其他数据转字符串
>>> str(123)
'123'
>>> str(3.14)
'3.14'
>>> str(print)
'<built-in function print>'
bool():
将其他数据转布尔类型
# 对于数值类型的话 非0全是True 0就是False
>>> bool(1)
True
>>> bool(-1)
True
>>> bool(0)
False
>>> bool(3.14)
True
>>> bool(-3.14)
True>>> bool(0.0)
False
# 对字符串 空串为False 非空为True
>>> bool("abc")
True
>>> bool("") #空串
False
进制转换
>>> bin(123) # 转二进制字符串
'0b1111011'
>>> oct(123) # 转八进制字符串
'0o173'
>>> hex(123) # 转十六进制字符串
'0x7b'
>>> bin("123") # 参数必须是整数
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
>>> bin(3.14)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'float' object cannot be interpreted as an integer
字符与ASCII码转换
a~z A~Z 0~9 他们在ASCII中的编号都是连续的
ord():获取字符对应的ASCII码编号
>>> ord('a')
97
>>> ord('A')
65
>>> ord('0')
48
chr():根据给定的ASCII码编号获取对应的字符
>>> chr(98)
'b'
>>> chr(57)
'9'A = 10 B = 11 ...... F = 15
13 - D
chr(ord('A') + 13 - 10)
常见的数学计算
>>> abs(3.14) # 取绝对值
3.14
>>> abs(-3.14)
3.14
>>> pow(2, 4) # 求a 的 b 次幂
16
>>> pow(2.0, 4)
16.0
>>> pow(16, 0.5)
4.0
>>> max(1, 2, 3, 4) # 求最值问题
4
>>> min(1,2,3,4)
1
>>> round(3.14) #四舍五入
3
>>> round(3.51)
4