Python s Implied Line Continuation Inside Parentheses

Multiline f-string in Python

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!                          

Related videos on Youtube

Comments

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

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

    • What's the full description of E122?

    • or just tell your ide to increase the line character limit, or ignore that rule all together

    • I don't feel its a dupe.. f strings are not discussed there.

    • @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

    • 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

    • @Owlzy Isn't the answer the exact same: use parenthesis, not the line-continuation marker?

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

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

    • @NickT: That may be so but the so called duplicate doesn't mention this and it's not entirely obvious that it'll work.

    • I agree that this question should not have been marked as a duplicate and closed. The duplicate referenced is not the same.

    • The linked question has ABSOLUTELY NOTHING TO DO with what was asked here. This one should not have been closed.

  • now that its closed i can delete this answer if people think i should ... but its not covered in the dupe answer :/\

  • 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

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

  • Wouldn't the \n cause problems in Windows? Is there a way to do this without the Unix-specific \n?

  • No problems on Windows. The \n is platform agnostic as Python has had universal newlines enabled by default since 3.0.

  • Oh yes, I tried this and it worked. Forgot to update here. Good old Python :').

  • Looks nice, but creates problems with indentation and code layout.

  • mix this with the builtin inspect.cleandoc function and you'll have a good day :)

  • 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").

  • 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!

  • 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,

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

Recents

Related

byrdhatuars.blogspot.com

Source: https://9to5answer.com/multiline-f-string-in-python

0 Response to "Python s Implied Line Continuation Inside Parentheses"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel