- 进制转换
- 类型转换
- 编码转换
a、进制转换
1、二进制 bin() 0b开头
a = 9#十进制8转换二进制 print(bin(a)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 0b1001 [Done] exited with code=0 in 0.028 seconds
2、八进制 oct() 0o开头
a = 9 #将十进制转换成8进制 print(oct(a)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 0o11 [Done] exited with code=0 in 0.035 seconds
3、十进制 int()
a = 0b10101010 #将二进制转换成十进制 print(int(a)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 170 [Done] exited with code=0 in 0.057 seconds
4、十六进制 hex() 0x开头
a = 0b10101010 #将二进制转换成十六进制 print(hex(a)) [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 0xaa [Done] exited with code=0 in 0.072 seconds
以上方法其实都差不多,常用就熟悉了。
b、数据类型转换
1、转int()型
a = '8' #将字符串转数字 print(int(a)) b = 12.11 #讲浮点数转int print(int(b)) c = True #bool转int,True是1,False是0. print(int(c)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 8 12 1 [Done] exited with code=0 in 0.039 seconds
2、转float()型
a = '8' #将字符串转数字 print(float(a)) b = '12.11' #讲浮点数转int print(float(b)) c = True #bool转int,True是1,False是0. print(float(c)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 8.0 12.11 1.0 [Done] exited with code=0 in 0.033 seconds
3、转str()型
a = 8 #将数字转字符串 print(str(a)) b = '12.11' #讲浮点数转float print(str(b)) c = True #bool转字符串,True是字符,False是字符. print(str(c)) 结合: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 8 12.11 True [Done] exited with code=0 in 0.053 seconds
4、转bool()型
a = 8 print(bool(a)) b = '12.11' print(bool(b)) c = True print(bool(c)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" True True True [Done] exited with code=0 in 0.034 seconds
bool类型特殊:0、空字符、None、空列表、空元祖、空字典、空集合都为False,其他都为True.
c、编码转换
1、ord("字符") 获取字符在ASCLL中对应的数值
a = 'a' #ASCLL中a对应的数值 print(ord(a)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" 97 [Done] exited with code=0 in 0.026 seconds
2、chr(数值) 获取数值在ASCLL中对应的字符
a = 88 print(chr(a)) 结果: [Running] /usr/bin/python3 "/home/zhi/桌面/python/dome.py" X [Done] exited with code=0 in 0.029 seconds