Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to put backslash escape sequence into f-string

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?

like image 224
Abhay Jain Avatar asked Feb 12 '21 13:02

Abhay Jain


2 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'
>>>
like image 142
AKX Avatar answered Oct 27 '22 00:10

AKX


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}"
like image 25
ApplePie Avatar answered Oct 26 '22 23:10

ApplePie