小编PYe*_*Yer的帖子

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

我一直在搞文本对齐,包括字符串方法和 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)

(第 …

python python-3.x f-string

2
推荐指数
2
解决办法
50
查看次数

标签 统计

f-string ×1

python ×1

python-3.x ×1