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?
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.
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 { }.
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.
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."
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}"
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With