Search code examples
python-3.xf-string

python 3.12 f-string inelegance


MY_WIDTH = 80
MY_CONSTRUCTED_HDR = f"this is a hdr of length {MY_WIDTH}"
print(MY_CONSTRUCTED_HDR)

this is a hdr of length 80 # YES, but NOT what I need -- see below I want something like this --

                   this is a hdr of length 80

and I miggghht even add another variable or two into the header at some point depending on how gabby the app is

Other constructs I tried --

#MY_CONSTRUCTED_HDR = f"this is a hdr of length {MY_WIDTH} : ^{MY_WIDTH}" # NO prints : ^80

#MY_CONSTRUCTED_HDR = f"{this is a hdr of length {MY_WIDTH}" : ^{MY_WIDTH}} # NO prints : ^80, lots of highlighted syntax errors

#MY_CONSTRUCTED_HDR = f"(this is a hdr of length {MY_WIDTH}" : ^{MY_WIDTH}) # NO prints : ^80, syntax errors

#MY_CONSTRUCTED_HDR = f"{'this is a hdr of length {MY_WIDTH}' : ^{MY_WIDTH}}" # this is CLOSE, prints centered BUT MY_WIDTH in header prints MY_WIDTH, not 80

#MY_CONSTRUCTED_HDR = f"{'this is a hdr of length {MY_WIDTH:2d}' : ^{MY_WIDTH}}" # NO, centers but prints MY_WIDTH:2d

This works but it's two steps:

hdr_string = f"this is a hdr of length {MY_WIDTH}"
MY_CONSTRUCTED_HDR = f"{hdr_string: ^{MY_WIDTH}}" # 
print(MY_CONSTRUCTED_HDR)

Really would like one line of code any ideas? f-strings preferred bc the header text and variables can change radically


Solution

  • You can use a nested f-string, with the outer f-string formatting the inner f-string:

    MY_WIDTH = 80
    print(f"{f"this is a hdr of length {MY_WIDTH}":^{MY_WIDTH}}")
    

    Note that prior to Python 3.12, you cannot use the same quotation mark for an outer f-string, so you would have to do something like:

    print(f'{f"this is a hdr of length {MY_WIDTH}":^{MY_WIDTH}}')