How to put backslash escape sequence into f-string

Viewed 1811

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?

3 Answers

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}"

You could assign the 15 tags to a variable and then use the variable in the f-string:

>>> tabs = "\t"*15
>>> f"{tabs}MESSAGE{tabs}"
>>> f"{tabs}MESSAGE{tabs}" == "{}MESSAGE{}".format("\t"*15, "\t"*15)
>>> True
Related