Multiline f-strings are similar to using single line f-strings in Python. It's just that the string should be mentioned within the parenthesis, i.e., the curly braces. Also, every line containing the f-string should be started with an f .
Multiline Python f Strings 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.
The f-string was introduced(PEP 498). In short, it is a way to format your string that is more readable and fast. Example: The f or F in front of strings tells Python to look at the values inside {} and substitute them with the values of the variables if exist.
Python f-string escaping charactersTo escape a curly bracket, we double the character. A single quote is escaped with a backslash character.
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()
.
I think it would be
return f'''{self.date} - {self.time},
Tags: {self.tags},
Text: {self.text}'''
You can use either triple single quotation marks or triple double quotation marks, but put an f at the beginning of the string:
return f'''{self.date} - {self.time},
Tags:' {self.tags},
Text: {self.text}'''
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.
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
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!
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