Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What is the logic behind this fstring in python?

From this question: Converting an integer to signed 2's complement binary string

we have this code:

def f(n):
    nbits = n.bit_length() + 1
    return f"{n & ((1 << nbits) - 1):0{nbits}b}"

I’m looking for some explanation/reference reading on the f string. In particular, what is the purpose of the :, the 0{...} syntax and the b?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

: separates the value to be printed from the format specification.

In a format specification, the last character specifies the type of formatting; in this case, b means binary. A number before that specifies the field with; in this case it’s the value of the nbits variable (nested {expression} are expanded and used as part of the format specification). And a leading zero before the field width means to padd with zeroes.

So this prints (1 << nbits) - 1 in binary in a field that’s nbits wide with leading zeroes.

The leading zeroes in the specification don’t seem relevant, because the value being printed will be nbits 1’s — there won’t be any need for padding.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading