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?
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.
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.
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?
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.
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.