1
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

2
  • 4
    I might recommend looking at the formatting of this question/revising it because it is not clear what you are asking about, some of which may be more clear if the formatting was fixed up. Are you trying to right-align something? Commented Mar 15, 2024 at 0:48
  • Apparently you want the string to be padded with leading and trailing spaces. Showing it in quotation marks rather than just indented would make that clearer: " this is a hdr of length 80 " (though the line wrapping in this comment doesn't help). Commented Mar 15, 2024 at 1:15

1 Answer 1

1

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}}')
Sign up to request clarification or add additional context in comments.

1 Comment

weird, but this is the way. thank you blhsing

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.