Search code examples
pythonpython-3.xstring-formattingnumber-formatting

Modifying the leading character in a formatted number in Python?


I know that in Python 3.6+ we can use f-strings to format numbers with a width and precision:

f"{value:{width}.{precision}}"

So I did the following:

>>> print(f"My number: {31072021:015.1f}")
My number: 00000031072021.0

Now if I try the same code without a 0 before the 15 in the {width} specifier, then I get the following

>>> print(f"My number: {31072021:15.1f}")
My number:       31072021.0

Now, is it possible to specify my own padding character instead of the default space or zero 0 characters?

Thanks for the help!


Solution

  • Yes, it is possible to add a padding character of your liking in python, but not with the format string alone. We would have to use rjust() for that.

    >>> s = f"{31072021:.1f}".rjust(15, 'a')
    'aaaaa31072021.0'
    
    >>> # same as: s="{:.1f}".format(31072021).rjust(15, "a")
    
    >>> print("My number:", s)
    My number: aaaaa31072021.0
    

    In your answer, the zero 0 padding appears because prepended zeros do not change the value of a number, so you will have the same value regardless of whether it is a space or a zero 0.