Search code examples
pythonprintingpaddingf-string

f string padding based on space instead of number of characters


My question is related to the question How can I fill out a Python string with spaces?. The answer coming closest to what I need is this one:

value = 4

print(f'foo {value:<10} bar')

However, a problem arises when the characters take up different spaces in my font choice. The padding no longer assures alignment of the 'bar' strings:

print(f'foo {value:<10} bar') # foo 4          bar
print(f'fii {value:<10} bar') # foo 4         bar

I want this:

print(f'foo {value:<10} bar') # foo 4          bar
print(f'fii {value:<10} bar') # foo 4          bar

How can I make sure that "bar" is aligned in both print statements independently of the length of "foo"? Basically, I want padding based on space not on the number of characters.

Specifically, I try to align the "n=" in my matplotlib legend labels:

label_i = f"{project_name:<10} n={sample_size}: rho={rho:.2f}"

Solution

  • Numbers will align with one another, which is why:

    print(f'fii {value:10d} bar')
    label_i = f"{project_name:10s} n={sample_size}: rho={rho:.2f}"
    

    Lines up "100" and "4":

    #fii          4 bar
    #test       n=100: rho=0.50
    

    Potential solutions to this are to manually assign the string:

    label_i = f"{project_name:12} n={sample_size}: rho={rho:.2f}"
    

    or alternatively, make use of tabs:

    print(f'fii \t\t {value} bar')
    label_i = f"{project_name}\t\t n={sample_size}: rho={rho:.2f}"
    

    Both of which have this output:

    #fii         4 bar
    #test        n=100: rho=0.50