繁体   English   中英

python 字符串中的二进制格式

[英]Binary formatting in python strings

在普通的 python %-formatted string 中是否无法进行二进制格式化? 例如:

>>> "Here is %b" % 4
ValueError: unsupported format character 'b' (0x62) at index 9

我知道你可以使用 f-strings / format-strings:

>>> f"Here is {4:b}"
'Here is 100'

>>> "Here is {num:b}".format(num=4)
'Here is 100'

但是有没有办法用 %-string 做到这一点?

不,您不能使用 %b 进行二进制格式化。 您需要使用 python bin(number) function ,它将返回该数字的二进制文件,前面为“0b”。 你可以做 bin(number)[2:] 来切掉 0b。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM