相关疑难解决方法(0)

嵌套的f字符串

感谢David Beazley的推文,我最近发现新的Python 3.6 f字符串也可以嵌套:

>>> price = 478.23
>>> f"{f'${price:0.2f}':*>20s}"
'*************$478.23'
Run Code Online (Sandbox Code Playgroud)

要么:

>>> x = 42
>>> f'''-{f"""*{f"+{f'.{x}.'}+"}*"""}-'''
'-*+.42.+*-'
Run Code Online (Sandbox Code Playgroud)

虽然我很惊讶这是可能的,但我很遗憾这是多么实际,何时嵌套f字符串是有用的?这可以涵盖哪些用例?

注意:PEP本身没有提到嵌套f字符串,但是有一个特定的测试用例.

python string-formatting python-3.x python-3.6 f-string

44
推荐指数
6
解决办法
8765
查看次数

我将如何为 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
查看次数