0

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?

2
  • Do you mean combine the two together? Commented Oct 18, 2020 at 5:17
  • Yes, I believe. Commented Oct 18, 2020 at 19:14

1 Answer 1

1

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

1 Comment

I just updated my question to be more clear, but thanks for the help.

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.