pythonf-string

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


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