gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 16:31:47 24 4
gpt4 key购买 nike

我想写一些简单的东西

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

关于python - 如何将反斜杠转义序列放入 f-string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66173070/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com