Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I set a python f-string format programmatically?

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?)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading