Multiline f-string in Python

110,920

Solution 1

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().

Solution 2

I think it would be

return f'''{self.date} - {self.time},
Tags: {self.tags},
Text: {self.text}'''

Solution 3

You can use either triple single quotation marks or triple double quotation marks, but put an f at the beginning of the string:

Triple Single Quotes

return f'''{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}'''

Triple Double Quotes

return f"""{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}"""

Notice that you don't need to use "\n" because you are using a multiple-line string.

Solution 4

As mentioned by @noddy, the approach also works for variable assignment expression:

var1 = "foo"
var2 = "bar"
concat_var = (f"First var is: {var1}"
              f" and in same line Second var is: {var2}")
print(concat_var)

should give you:

First var is: foo and in same line Second var is: bar

Solution 5

You can mix the multiline quoting styles and regular strings and f-strings:

foo = 'bar'
baz = 'bletch'
print(f'foo is {foo}!\n',
      'bar is bar!\n',
      f"baz is {baz}!\n",
      '''bletch
      is
      bletch!''')

Prints this (note the indentation):

foo is bar!
 bar is bar!
 baz is bletch!
 bletch
      is
      bletch!
Share:
110,920

Related videos on Youtube

Owlzy
Author by

Owlzy

Updated on November 09, 2021

Comments

  • Owlzy
    Owlzy about 1 year

    I'm trying to write PEP-8 compliant code for a domestic project and I have a line with an f-string that is more than 80 characters long

    - the solid thin line near the dot at self.text is the 80 char mark.

    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?

    • Nick stands with Ukraine
      Nick stands with Ukraine over 5 years
      You dont have to return it all on one line, create a base string in a variable then append each part using +=. Then just return the variable. The reason it doesnt comply with E122 is possibly because you aren't indenting the following line.
    • MaddTheSane
      MaddTheSane over 5 years
      What's the full description of E122?
    • Joran Beasley
      Joran Beasley over 5 years
      or just tell your ide to increase the line character limit, or ignore that rule all together
    • Ma0
      Ma0 over 5 years
      I don't feel its a dupe.. f strings are not discussed there.
    • Owlzy
      Owlzy over 5 years
      @JoshLee "E122 continuation line missing indentation or outdented main" also why you closed the question? There are no duplicates, its the only one about multiline f-strings
    • Owlzy
      Owlzy over 5 years
      for the others, this isnt a question about the code, is a question about how to makes multilines f-string looks good and pep-8 compliant without cheesy hacks and non-pythonic styles
    • Nick T
      Nick T over 5 years
      @Owlzy Isn't the answer the exact same: use parenthesis, not the line-continuation marker?
    • Nick T
      Nick T over 5 years
      Also, please clarify if you are talking about a string with linebreaks in it (\n) or a multi-line string literal (which you don't have, you just added a couple single-line f-string literals).
    • Urda
      Urda over 4 years
      This question should have never been closed as a dupe, as the linked 'dupe' ins't a dupe of this question. Stackoverflow power users you know that we have an issue about being too aggressive like this, get it re-opened. Casting a re-open vote ASAP.
    • ChrisWue
      ChrisWue over 4 years
      @NickT: That may be so but the so called duplicate doesn't mention this and it's not entirely obvious that it'll work.
    • John Forbes about 4 years
      I agree that this question should not have been marked as a duplicate and closed. The duplicate referenced is not the same.
    • Victor Schröder
      Victor Schröder almost 4 years
      The linked question has ABSOLUTELY NOTHING TO DO with what was asked here. This one should not have been closed.
  • Joran Beasley
    Joran Beasley over 5 years
    now that its closed i can delete this answer if people think i should ... but its not covered in the dupe answer :/\
  • Owlzy
    Owlzy over 5 years
    but this kind of multiline defeats the purpose of f-strings and indentation Also I dont feel like this is the right use of the triple quote strings, feels like an hack
  • Mike Williamson
    Mike Williamson about 3 years
    While this answer does replicate the OP's intent, I feel like @noddy's answer is better. This answer just happens to be correct because the OP also wanted multi-line in the output. If you wanted the output to have a different layout than the source code, triple quotes are not the way to go.
  • shinvu
    shinvu almost 2 years
    Wouldn't the \n cause problems in Windows? Is there a way to do this without the Unix-specific \n?
  • noddy almost 2 years
    No problems on Windows. The \n is platform agnostic as Python has had universal newlines enabled by default since 3.0.
  • shinvu
    shinvu almost 2 years
    Oh yes, I tried this and it worked. Forgot to update here. Good old Python :').
  • DZet
    DZet over 1 year
    Looks nice, but creates problems with indentation and code layout.
  • Zack Plauché
    Zack Plauché over 1 year
    mix this with the builtin inspect.cleandoc function and you'll have a good day :)
  • cellepo
    cellepo over 1 year
    Good point about "\n" - and here is another reference that also explains it's not necessary for multiline Strings (in section, "Multiline Strings with Triple Quotes").
  • Mattias Wallin
    Mattias Wallin about 1 year
    Keep in mind that this is probably less efficient than doing one big f-string, because of extra intermediate (de-)allocations and copying. But it is a good tradeoff for more readable code!
  • questionto42standswithUkraine
    questionto42standswithUkraine 9 months
    The \n only works if you use print(...), but not, when using return (...). Then \n is shown in the output, it is not understood as newline. No need to say, it is still working if you just print the return value. Another idea is in this answer,
  • Stevoisiak
    Stevoisiak 7 months
    What's the recommended style if only some lines contain variables? Should f only be added to the lines that have variables or should it be on every line for consistency?