Search code examples
pythonpython-3.xf-string

How would I define a fill character for f-string alignment?


I've been messing around with text-alignment, including the string methods, and f-strings. My current goal is to create a table of contents styled output, that looks something like this:

Introduction....................1
Python Basics...................5
Creating Your First Program....12
Operators and Variables........29

Easily enough, I've been able to format it like:

Introduction                    1
Python Basics                   5
Creating Your First Program    12
Operators and Variables        29

The code being:

for chapt, page in contents:
  print(f"{chapt:<30}{page:>5}")

I can't find any resources on the web that describe how to add a fill character and f-strings together. Using the .center, .ljust, .rjust string methods, I have been able to do this, as they take the parameter of width and then an optional fill character. On this post, I thought I found a solution.

The x<y portion signifies to left-align the text with a width of y spaces. For any unused space, pad it with character x.

I tried this method, editing my print statement from print(f"{chapt:<30}{page:>5}") to print(f"{chapt:'.'<30}{page:'.'>5}"). Yet this returns an error:

Traceback (most recent call last):
  File "main.py", line 40, in <module>
    print(f"{chapt:'.'<30}{page:'.'>5}")
ValueError: Invalid format specifier

(Line 40 being the line in my full code.)

Is there any way to choose a fill character, or would I have to revert to the string methods. I believe there is, but I can not figure out how to use it. Thanks!


Solution

  • Specify it before the alignment character (> or <), without apostrophes.

    contents = {"Introduction": 1, "Python Basics": 5, "Creating Your First Program": 12, "Operators and Variables": 29}
    for chapt, page in contents.items():
        print(f"{chapt:.<30}{page:.>5}")
    

    Outputs:

    Introduction......................1
    Python Basics.....................5
    Creating Your First Program......12
    Operators and Variables..........29
    

    From the documentation

    If a valid align value is specified, it can be preceded by a fill character that can be any character and defaults to a space if omitted. It is not possible to use a literal curly brace (“{” or “}”) as the fill character in a formatted string literal or when using the str.format() method. However, it is possible to insert a curly brace with a nested replacement field. This limitation doesn’t affect the format() function