首页 > 解决方案 > 如何将反斜杠转义序列放入 f 字符串

问题描述

我想写一些简单的东西

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

我怎样才能做到这一点?

标签: pythonstringf-string

解决方案


你可能会看到这个:

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

推荐阅读