Abh*_*ain 5 python string f-string
我想写一些简单的东西
"{}MESSAGE{}".format("\t"*15, "\t"*15)
Run Code Online (Sandbox Code Playgroud)
使用
f"{'\t'*15}MESSAGE{'\t'*15}" # This is incorrect
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
"{}MESSAGE{}".format("\t"*15, "\t"*15)
Run Code Online (Sandbox Code Playgroud)
我怎样才能做到这一点?
正如错误消息所示,反斜杠与 f 字符串不兼容。只需将制表符放入变量中并使用它即可。
tab = '\t' * 15
f"{tab}MESSAGE{tab}"
Run Code Online (Sandbox Code Playgroud)
你可能会看到这个:
>>> 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
Run Code Online (Sandbox Code Playgroud)
为了简单起见,f 字符串表达式不能包含反斜杠,因此您必须这样做
>>> 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'
>>>
Run Code Online (Sandbox Code Playgroud)