Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write an f-string on multiple lines without introducing unintended whitespace? [duplicate]

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?

like image 888
Kurt Peek Avatar asked Mar 21 '18 20:03

Kurt Peek


People also ask

How do you make a multi line F string?

You can create a multiline Python f string by enclosing multiple f strings in curly brackets. In our code, we declared three variables — name, email, and age — which store information about our user. Then, we created a multiline string which is formatted using those variables.

How do you escape quotes in F string?

4.1. We can use any quotation marks {single or double or triple} in the f-string. We have to use the escape character to print quotation marks. The f-string expression doesn't allow us to use the backslash. We have to place it outside the { }.

How do I write a string to multiple lines in Python?

You can have a string split across multiple lines by enclosing it in triple quotes. Alternatively, brackets can also be used to spread a string into different lines. Moreover, backslash works as a line continuation character in Python. You can use it to join text on separate lines and create a multiline string.

How do you wrap a long f string in Python?

To add to that: "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."


1 Answers

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}"
         )
like image 117
Prune Avatar answered Oct 03 '22 09:10

Prune