126

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?

2
  • 3
    This is indeed a partial duplicate, but the duplicate does not pertain to f strings, a slight modification is needed to that answer. Commented Feb 20, 2018 at 8:58
  • @cs95 I don't see why. All the same techniques work fundamentally the same way with f-strings. Commented May 24, 2024 at 2:44

2 Answers 2

212

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.

Sign up to request clarification or add additional context in comments.

9 Comments

The first line should not have an f
@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.
Some tools will complain if you have an f-string with no actual interpolation (pylint or mypy does this, I think). You may need to tell the tool to not complain about that line.
@paxdiablo pylint does, but I don't hink mypy does
|
21

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.

3 Comments

"But f will need to be prepended to the second line"- why?
@Chris_Rands Otherwise, the second line is treated as a literal string, and the variable is not substituted in.
In your answer, you have a multiline string, so it is not required.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.