I want to write something as simple as
"{}MESSAGE{}".format("\t"*15, "\t"*15)
using
f"{'\t'*15}MESSAGE{'\t'*15}" # This is incorrect
but I get the following error:
>>> something = f"{'\t'*6} Weather"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
>>> something = f"{\'\t\'*6} Weather"
File "<stdin>", line 1
SyntaxError: f-string expression part cannot include a backslash
How can I do this?
You're probably seeing this:
>>> f"{'\t'*15}MESSAGE{'\t'*15}"
File "<stdin>", line 1
f"{'\t'*15}MESSAGE{'\t'*15}"
^
SyntaxError: f-string expression part cannot include a backslash
For simplicity's sake, f-string expressions can't contain backslashes, so you'll have to do
>>> spacer = '\t' * 15
>>> f"{spacer}MESSAGE{spacer}"
'\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tMESSAGE\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t'
>>>
As the error messages says, backslashes are not compatible with f strings. Simply put the tab character in a variable and use this.
tab = '\t' * 15
f"{tab}MESSAGE{tab}"
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