What is the difference between the bin() and f string {:b} format

Viewed 21

for instance this code

i = 16

print(len(bin(i)))
print(len(f'{i:b}'))

prints 7 and 5 respectively. Is it not converting an int into binary representation on both occasions? why is the length different?

Edit: I'm a complete smooth brain. I've been working on beginner python challenges and despite what it might look like, It genuinely did not occur to me to just print it and see the difference. Frustration and mental fatigue got the better of me. Cheers to everyone who took the time to answer my stupid question.

1 Answers

Print the actual values, not the lengths, and it's really obvious. bin adds a 0b prefix to the string, :b alone does not. It's still the binary representation either way (neither is wrong), one of them just explicitly includes the prefix.

If you add a # to the format spec, making it f'{i:#b}', the f-string is equivalent. This works for x and o formats as well, so they match hex and oct respectively.

Related