7

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?

khelwood
  • 55,782
  • 14
  • 81
  • 108
Abhay Jain
  • 119
  • 1
  • 10

3 Answers3

3

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'
>>>
AKX
  • 152,115
  • 15
  • 115
  • 172
3

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}"
ApplePie
  • 8,814
  • 5
  • 39
  • 60
1

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
Karl Sutt
  • 575
  • 3
  • 11