Multiline f-string in Python

Owlzy picture Owlzy · Aug 30, 2017 · Viewed 35.8k times · Source

I'm trying to write PEP-8 compliant code for a domestic project (I must admit that those are my first steps in the python world) and i've got a f-string that is more than 80 char long

- the solid thin line near the dot at self.text is the 80 char mark. (Sorry for the sad link without preview but i must have 10+ rep to post 'em)

I'm trying to split it into different lines in the most pythonic way but the only aswer that actually works is an error for my linter

Working Code:

def __str__(self):
    return f'{self.date} - {self.time},\nTags:' + \
    f' {self.tags},\nText: {self.text}'

Output:

2017-08-30 - 17:58:08.307055,
Tags: test tag,
Text: test text

The linter thinks that i'm not respecting E122 from PEP-8, is there a way to get the string right and the code compliant?

Answer

noddy picture noddy · Mar 1, 2019

From Style Guide for Python Code:

The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces.

Given this, the following would solve your problem in a PEP-8 compliant way.

return (
    f'{self.date} - {self.time}\n'
    f'Tags: {self.tags}\n'
    f'Text: {self.text}'
)

Python strings will automatically concatenate when not separated by a comma, so you do not need to explicitly call join().