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

PythonPython 3.xStringF String

Python Problem Overview


I am getting a line too long PEP 8 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 PEP 8 linting?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiontreadView Question on Stackoverflow
Solution 1 - Pythonjuanpa.arrivillagaView Answer on Stackoverflow
Solution 2 - Pythoncs95View Answer on Stackoverflow