如何将反斜杠转义序列放入 f-string

问题描述

我想写一些简单的东西

"{}MESSAGE{}".format("\t"*15,"\t"*15)

使用

f"{'\t'*15}MESSAGE{'\t'*15}" # This is incorrect

但我收到以下错误

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

我该怎么做?

解决方法

您可能会看到:

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

为简单起见,f-string 表达式不能包含反斜杠,所以你必须这样做

>>> 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'
>>>
,

正如错误消息所说,反斜杠与 f 字符串不兼容。只需将制表符放在一个变量中并使用它。

tab = '\t' * 15
f"{tab}MESSAGE{tab}"
,

您可以将 15 个标签分配给一个变量,然后在 f 字符串中使用该变量:

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