每日一课 | Python将int转换为二进制字符串

本文介绍了Python中使用bin()和format()函数将整数转换为二进制字符串的方法,包括带有前缀'0b'的表示,填充零至特定位数,以及转换为十六进制和八进制的表示。示例代码详细展示了各种转换方式。
摘要由CSDN通过智能技术生成

在Python中,我们可以使用bin()format()将整数转换为二进制字符串表示形式。

print(bin(1)) # 0b1
  print(bin(-1)) # -0b1
  print(bin(10)) # 0b1010
  print(bin(-10)) # -0b1010
 
  print("{0:b}".format(10)) # 1010
  print("{0:#b}".format(10)) # 0b1010 , with 0b prefix
  print("{0:b}".format(10).zfill(8)) # 00001010 , pad zero, show 8 bits
  print(format(10, "b")) # 1010
  print(format(10, "#b")) # 0b1010, with 0b prefix
  print(format(10, "b").zfill(16)) # 0000000000001010, pad zero, show 16 bits

  # with hex, oct bin
  # int: 10; hex: a; oct: 12; bin: 1010
  result = "int: {0:d}; hex: {0:x}; oct: {0:o}; bin: {0:b}".format(10)
  print(result)

  # with 0x, 0o, or 0b as prefix:
  # int: 10; hex: 0xa; oct: 0o12; bin: 0b1010
  result = "int: {0:d}; hex: {0:#x}; oct: {0:#o}; bin: {0:#b}".format(10)
  print(result)

参考文献:

  1. Python bin文件

  2. Python格式文件

  3. Python格式规范迷你语言

翻译自: https://mkyong.com/python/python-how-to-convert-int-to-a-binary-string/

推荐阅读--

每周一课 | Python 示例拆分字符串入到字典里面

每日一课 | 如何将String转换为int

每日一课 | Python time.sleep 精准延迟到秒

每日一课 | Python 如何判断一个字符串是否包含另一个字符串?

球分享

球点赞

球在看

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值