How to put backslash escape sequence into an f-string
If you want to write something like:
"{}MESSAGE{}".format("\t"*15, "\t"*15)
but using f-strings, you hit the issue that you cannot have a backslash inside an f-string expression.
Instead you should assign the tab character to a variable and then use that:
tab = '\t' * 15
f"{tab}MESSAGE{tab}"
Update: PEP 701, implemented in Python
3.12 (October 2023), removes this restriction entirely — backslashes (and even
same-type nested quotes) are now legal directly inside f-string expression
braces. On Python 3.12+ you can write f"{'\t' * 15}MESSAGE{'\t' * 15}"
directly. The workaround above is still needed if you’re on Python 3.11 or
earlier.
Via SO.
Leave a comment