1

I'm writing to a text file where i want a field of a formatted string to be left-justified AND have 2-digit float precision.

Sample input (does not work):

txt = "We have {:.2f <8} chickens."
print(txt.format(0.123124234123412341324))

Desired output:

0.12 (left justified, with 8 spaces)
2
  • I may be misunderstanding your goal, but have you tried {:<8.2f}? Commented Aug 10, 2020 at 14:41
  • Thanks, that works! Commented Aug 10, 2020 at 14:42

1 Answer 1

3

Per the Python Format Specification Mini-Language, alignment specifiers (e.g. <) and width specifiers (e.g. 8) must precede the floating point precision specifier (e.g. .2). With this criteria in mind, the correct formulation for your format string is {:<8.2f}:

txt = "We have {:<8.2f} chickens."
print(txt.format(0.123124234123412341324))

Output:

We have 0.12     chickens.
Sign up to request clarification or add additional context in comments.

Comments

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.