Guidance with f-string formatting documentation

104 Views Asked by At

I'm currently playing around with f-strings more and trying to figure out how to do things like

# Depth and decimal format
f"string text {var: #.#f}"

# Alignment format
f"string text {var: < #}"

I know that is how you would do a depth, decimal, and alignment format for a variable, but how would one format the string text and variable together? Such as

f"num = {dartsThrown: < 10d}"
print((f"num ={dartsThrown: < 10d}  Calculated PI = {computePI(dartsThrown):.6f}   "
       f"Difference = {differencePI:+0.6f}"))

how do you combine f-string formatting to both 'num = ' and {var}

Would I have to store it into a variable itself?

numVariable = 'num = ' + dartsThrown

f"{numVariable: < ##d}"

or is there another way to do it?

1

There are 1 best solutions below

1
On

You can put the alignment specification before the width specification, per the documentation of the Format Specification Mini-Language:

>>> var=1.23
>>> f'{var:<8.1f}'
'1.2     '
>>>