简体   繁体   English

python 字符串中的二进制格式

[英]Binary formatting in python strings

Is it not possible to do binary formatting in a normal python %-formatted string?在普通的 python %-formatted string 中是否无法进行二进制格式化? For example:例如:

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

I know you can using f-strings / format-strings:我知道你可以使用 f-strings / format-strings:

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

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

But is there a way to do this with the %-string?但是有没有办法用 %-string 做到这一点?

No you cannot do binary formatting using %b.不,您不能使用 %b 进行二进制格式化。 You need to use the python bin(number) function which will return binary of that number preceeded by "0b".您需要使用 python bin(number) function ,它将返回该数字的二进制文件,前面为“0b”。 you could do bin(number)[2:] to slice off 0b.你可以做 bin(number)[2:] 来切掉 0b。

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

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