Home > Software design >  What is the logic behind this fstring in python?
What is the logic behind this fstring in python?

Time:02-08

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?

CodePudding user response:

: 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.

  •  Tags:  
  • Related