Reputation: 3
I'm very new to Python, and trying to understand f-strings. In a related thread, several people describe how to use f-strings to convert an integer to binary with a fixed length. However, I am trying to convert from integer to binary using a variable length. Note that the number of bits specified will never be less than the minimum required to express the integer in binary form.
The example in the linked thread gives something similar to this:
s = 6
l = 7
a = '{0:07b}'.format(6)
print(a)
a = f'{s:07b}'
print(a)
which outputs
0000110
0000110
But I want to change the string length to a variable number of bits. So, for a length of 3 bits, the same methods above should give
s = 6
l = 7
a = '{0:03b}'.format(6)
print(a)
a = f'{s:03b}'
print(a)
110
110
I've tried
s = 6
l = 7
a = f'{s:0%b}' %3
print(a)
and
s = 6
l = 7
a = f'{s:0%b}' %l
print(a)
but doing so gives me this error
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-569-dc7a52b74c19> in <module>
1 s = 6
2 l = 7
----> 3 a = f'{s:0%b}' %l
4 print(a)
ValueError: Invalid format specifier
I don't know what I'm doing wrong, as using '%' in other f-string contexts seems to work fine. I appreciate any help!
Upvotes: 0
Views: 1551
Reputation: 44838
You can nest {}
formats in f-strings:
>>> s = 6
>>> l = 7
>>> a = f'{s:0{l}b}'
>>> print(a)
0000110
Upvotes: 2