如何拆分 Python 中的长 f 字符串?

How can I split up a long f-string in Python?

我收到一个 行太长 PEP 8 E501 问题。

f'Leave Request created successfully. Approvers sent the request for approval: {leave_approver_list}'

我尝试使用多行字符串,但这会带来 \n,这会破坏我的测试:

f'''Leave Request created successfully.
Approvers sent the request for approval: {leave_approver_list}'''

如何让它保持单行并通过 PEP 8 linting?

除非将字符串括在括号中,否则您将需要换行符。在这种情况下,需要将 f 添加到第二行:

'Leave Request created successfully.'\
f'Approvers sent the request for approval: {leave_approver_list}'

这是一个小演示:

In [97]: a = 123

In [98]: 'foo_'\
    ...: f'bar_{a}'
Out[98]: 'foo_bar_123'

我推荐 ,因为它更干净,但这是一种方法。

使用括号和 string literal concatenation:

msg = (
         f'Leave Request created successfully. '
         f'Approvers sent the request for approval: {leave_approver_list}'
)

请注意,第一个文字不需要 f,但我将其包含在 consistency/readability 中。