0

I would like to set the formatting of a large integer in an fstring programmatically. Specifically, I have an integer that can span several orders of magnitude and I'd like to print it using the underscore "_" delimiter, e.g.

num = 123456789
print(f"number is {num:9_d}")
>>> number is 123_456_789   # this is ok

num = 1234
print(f"number is {num:9_d}")
>>> number is     1_234   # this has extra spaces due to hand-picking 9

How can I set the number preceding "_d" programmatically based on the number of digits in num? (Or in case I asked an XY question, how can I print the number with underscore delimiters and no extra spaces?)

5
  • 2
    You can just drop the length specifier. Commented Jul 25, 2024 at 16:38
  • Alternatively, you can left justify the number with {num:<9_d}, though this will leave trailing spaces on the right side. Commented Jul 25, 2024 at 16:39
  • Why add 9 at all then if you do not want spaces? Commented Jul 25, 2024 at 16:43
  • I'm mostly just informing on f-string parameters that OP may not be aware of. Commented Jul 25, 2024 at 16:45
  • Ooh I didn't know I could just have dropped the length specifier 😅. Thank you. Commented Jul 25, 2024 at 16:52

2 Answers 2

2

Like so:

v = 9
print(f"number is {num:{v}_d}")
Sign up to request clarification or add additional context in comments.

Comments

1

You could drop the length parameter altogether:

In [290]: num = 123456789

In [291]: print(f"number is {num:_d}")
number is 123_456_789

In [293]: num = 1234

In [294]: print(f"number is {num:_d}")
number is 1_234

But to answer the question as asked, you could format format string

In [295]: s = "number is {num:%d_d}" %len(str(num))  # the `%d` is used to format the length parameter, while the `_d` remains an f-string construct

In [297]: print(s.format(num=num))
number is 1_234

In [298]: print(s.format(num=123456789))
number is 123_456_789

Hope this helps

2 Comments

"Format format string" approach looks terrific, especially given that you can use variables in format specification...
Downvoted, because the question was how to do this with f-strings, not with format.

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.