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

Question:

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?

Asked By: tread

||

Answers:

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.

Answered By: cs95

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.

Answered By: juanpa.arrivillaga
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.