# What is the logic behind this fstring in python?

121
April 17, 2022, at 10:20 PM

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`?

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

POPULAR ONLINE

### How to switch to predict mode in Trax after training a model?

I'm familiarizing myself with the Trax library for building deep learning models and one question that I can't find an answer to is how to switch from "train" mode to "eval" mode after model training is complete

105

### Rotate point about another point in degrees python

If you had a point (in 2d), how could you rotate that point by degrees around the other point (the origin) in python?

195

### Seaborn Lineplot- Displaying Values on top of the markers

We could display a values from dataframe to the graph using the brand new feature of the matplotlib in bar graph

85

### Plotly: Scatter plot with dropdown menu and color by group

I'm trying to make a scatter plot with 2 dropdown menus that select a data column (from a pandas data frame) to be plotted for x and y-axis, but I'm also wanting the points to be colored by a third categorical variable that is fixed (no dropdown needed...

129