简体   繁体   中英

Binary formatting in python strings

Is it not possible to do binary formatting in a normal 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"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?

No you cannot do binary formatting using %b. You need to use the python bin(number) function which will return binary of that number preceeded by "0b". you could do bin(number)[2:] to slice off 0b.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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