69

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?

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
tread
  • 9,064
  • 16
  • 86
  • 149
  • 1
    This is indeed a partial duplicate, but the duplicate does not pertain to f strings, a _slight_ modification is needed to that answer. – cs95 Feb 20 '18 at 08:58

2 Answers2

121

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.

juanpa.arrivillaga
  • 77,035
  • 9
  • 115
  • 152
  • 11
    To add to that: [_"The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation."_](https://www.python.org/dev/peps/pep-0008/#maximum-line-length) – moooeeeep Feb 20 '18 at 09:15
  • The first line should not have an `f` – Aidan H Apr 09 '21 at 18:19
  • 6
    @AidanH why *should* it not? It makes no difference, so it comes down to a style choice. I prefer the `f` here so they line up. I can understand why people would feel otherwise, though. I actually *noted* this in the answer. – juanpa.arrivillaga Apr 09 '21 at 18:32
17

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.

Peter Mortensen
  • 30,030
  • 21
  • 100
  • 124
cs95
  • 330,695
  • 80
  • 606
  • 657