我将如何为 f 字符串对齐定义填充字符?

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

我一直在搞乱文本对齐,包括字符串方法和 f 字符串。我当前的目标是创建 table 内容样式输出,看起来像这样:

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

很简单,我已经能够将其格式化为:

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

代码为:

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

我在网上找不到任何描述如何将填充字符和 f 字符串一起添加的资源。使用 .center.ljust.rjust 字符串方法,我已经能够做到这一点,因为它们采用宽度参数,然后是可选的填充字符。 在 上,我以为我找到了解决方案。

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.

我尝试了这个方法,将我的打印语句从 print(f"{chapt:<30}{page:>5}") 编辑为 print(f"{chapt:'.'<30}{page:'.'>5}")。然而这 returns 一个错误:

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

(第 40 行是我完整代码中的那一行。)

有什么方法可以选择填充字符,或者我是否必须恢复到字符串方法。我相信有,但我不知道如何使用它。谢谢!

在对齐字符(><)之前指定它,不带撇号。

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}")

输出:

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

来自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

根据Format Specification Mini-Language你必须在“对齐”之前指定它:

contents = [('Introduction', 1), ('Python Basics', 5),
            ('Creating Your First Program', 12),
            ('Operators and Variables', 29)]

row_length = 35

for chapt, page in contents:
    dots = str(row_length - len(str(page)))
    print(f"{chapt:.<{dots}}{page}")

*这现在与 page 的长度无关。更灵活一点。