10

Consider the following code snippet:

name1 = "Nadya"
name2 = "Jim"

def print_string():
    string = f"{name1}\n\
{name2}"
    print(string)

print_string()

which produces

Nadya
Jim

This works, but the 'break' in indentation on the second line of the string definition looks ugly. I've found that if I indent the {name2} line, this indentation shows up in the final string.

I'm trying to find a way to continue the f-string on a new line and indent it without the indentation showing up in the final string. Following something similar I've seen for ordinary strings, I've tried

name1 = "Nadya"
name2 = "Jim"

def print_string():
    string = f"{name1}\n"
             f"{name2}"
    print(string)

print_string()

but this leads to an IndentationError: unexpected indent. Is what I am trying possible in another way?

Kurt Peek
  • 52,165
  • 91
  • 301
  • 526
  • 1
    You can use backslash line continuation outside the string, the exact same way you did inside the string in your first example. Then they're the same line to the parser, so there is no indentation issue. Or you can put otherwise-meaningless parens around the string and then you don't need backslashes (although some linters may complain because they assume that you were trying to make a tuple and forgot a comma). – abarnert Mar 21 '18 at 20:51
  • 2
    Also, do you know about triple-quoted strings? They work just as well for f-strings as for static strings. And, unless the values in `name1` and `name2` are going to be multi-line, all of the usual stuff like `textwrap.dedent` works fine with the evaluated f-string, so all of the decades of information on how to use triple-quoted strings effectively applies to most triple-quoted f-strings. – abarnert Mar 21 '18 at 21:00

1 Answers1

27
string = f"{name1}\n"   \   # line continuation character
         f"{name2}"

Update thanks to @cowbert, to adhere to PEP-8 recommendation:

string = (f"{name1}\n"
          f"{name2}"
         )
Prune
  • 76,765
  • 14
  • 60
  • 81
  • thank you. this worked for me. whereas, `dedent(` and `repr(dedent(` did not – Kermit Jan 21 '21 at 20:24
  • 7
    Downovted per PEP8: [The preferred way of wrapping long lines is by using Python's implied line continuation inside parentheses, brackets and braces. Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.](https://www.python.org/dev/peps/pep-0008/#maximum-line-length): `string = ( f"{name}\n" f"{name2}" )` – cowbert Mar 03 '21 at 18:34
  • ``` string = f""" {name1} {name2} """ ``` – Michael Lapping Nov 29 '21 at 21:41
  • This does not work for me. It prints "\n" when it shouldn't. – FaCoffee May 12 '22 at 08:52
  • What about when you have more than two lines? The () brackets gives error `"(" was not closed` – normal_human Apr 12 '23 at 04:57