How can I programmatically generate an f-string format specification? For example I'd like to zero pad this binary number up to n
bits:
>> n = 5
>> f"{6:05b}"
00110
>> n = 7
>> f"{6:07b}"
0000110
CodePudding user response:
Nested formatting works with f-strings as it did with the older format
function, as detailed in the Format String Syntax section of the docs:
A format_spec field can also include nested replacement fields within it. These nested replacement fields may contain a field name, conversion flag and format specification, but deeper nesting is not allowed. The replacement fields within the format_spec are substituted before the format_spec string is interpreted. This allows the formatting of a value to be dynamically specified.
Sadly, the docs don't include an example with f-strings. Here's one. Notice the nested curly braces:
for n in range(3, 8):
print(f"{6:0{n}b}")
Prints:
110
0110
00110
000110
0000110
CodePudding user response:
You can do it by defining the f-string to be the result of a function. This will delay its evaluation until the function is called:
template = lambda: f"{6:0{n}b}"
n = 5
print(template()) # -> 00110
n = 7
print(template()) # -> 0000110