如何在python中拆分长f字符串?

时间:2018-02-20 08:55:59

标签: python python-3.x string f-string

我收到line too long pep8 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}'''

如何保持单行并通过pep8 linting

3 个答案:

答案 0 :(得分:8)

使用括号和string literal concatenation

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

请注意,第一个文字不需要f,但我将其包含在内以保持一致性/可读性。

答案 1 :(得分:3)

只需添加反斜杠\字符:

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

答案 2 :(得分:3)

确实需要一个换行符。但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'