第九课、python进制转换(bin,oct,int,hex)、类型转换(int,float,str,bool)、编码转换(ord,chr)

  1. 进制转换
  2. 类型转换
  3. 编码转换

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

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

cyz141001

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值