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

PYe*_*Yer 2 python python-3.x f-string

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

Introduction....................1
Python Basics...................5
Creating Your First Program....12
Operators and Variables........29
Run Code Online (Sandbox Code Playgroud)

很容易,我已经能够将其格式化为:

Introduction                    1
Python Basics                   5
Creating Your First Program    12
Operators and Variables        29
Run Code Online (Sandbox Code Playgroud)

代码是:

Introduction....................1
Python Basics...................5
Creating Your First Program....12
Operators and Variables........29
Run Code Online (Sandbox Code Playgroud)

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

x<y部分表示将文本左对齐,宽度为 y 个空格。对于任何未使用的空间,用字符 x 填充它。

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

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

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

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

Sor*_*ary 7

根据格式规范迷你语言,您必须在“对齐”之前指定它:

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}")
Run Code Online (Sandbox Code Playgroud)

*现在这与page数字的长度无关。稍微灵活一点。


Pra*_*adi 5

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

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}")
Run Code Online (Sandbox Code Playgroud)

输出:

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}")
Run Code Online (Sandbox Code Playgroud)

文档

如果指定了有效的对齐值,则它前面可以是一个填充字符,该字符可以是任何字符,如果省略则默认为空格。在格式化字符串文字中或使用该方法时,不能使用文字花括号(“ {”或“ }”)作为填充字符。但是,可以插入带有嵌套替换字段的花括号。此限制不影响功能str.format()format()