How to split up a long f-string in python?

为君一笑 提交于 2020-05-12 11:18:07

问题


I am getting a line too long pep8 E501 issue.

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

I tried using a multi-line string, but that brings in a \n, which breaks my test:

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

How can I keep it single line and pass pep8 linting


回答1:


You will need a line break unless you wrap your string within parentheses. In this case, f will need to be prepended to the second line:

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

Here's a little demo:

In [97]: a = 123

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

I recommend juanpa's answer since it is cleaner, but this is one way to do this.




回答2:


Use parentheses and string literal concatenation:

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

Note, the first literal doesn't need an f, but I include it for consistency/readability.




回答3:


Just add a backslash \ character:

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


来源:https://stackoverflow.com/questions/48881196/how-to-split-up-a-long-f-string-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!