如何转义格式化 python 字符串中的单个反斜杠?

vae*_*r-k 5 python python-3.x python-3.6

在 Python 3.6 的格式化字符串结果中包含一对反斜杠时遇到一些问题。请注意,#1 和 #2 产生相同的不需要的结果,但 #3 会产生太多反斜杠,这是另一个不需要的结果。

1

t = "arst '{}' arst"
t.format(d)
>> "arst '2017-34-12' arst"
Run Code Online (Sandbox Code Playgroud)

2

t = "arst \'{}\' arst"
t.format(d)
>> "arst '2017-34-12' arst"
Run Code Online (Sandbox Code Playgroud)

3

t = "arst \\'{}\\' arst"
t.format(d)
>> "arst \\'2017-34-12\\' arst"
Run Code Online (Sandbox Code Playgroud)

我正在寻找如下所示的最终结果:

>> "arst \'2017-34-12\' arst"
Run Code Online (Sandbox Code Playgroud)

Oli*_*çon 4

你的第三个例子是正确的。您可以print通过它来确保这一点。

>>> print(t.format(d))
arst \'2017-34-12\' arst
Run Code Online (Sandbox Code Playgroud)

您在控制台中看到的实际上是字符串的表示形式。您确实可以通过使用来获取它repr

print(repr(t.format(d)))
"arst \\'2017-34-12\\' arst"
#     ^------------^---Those are not actually there
Run Code Online (Sandbox Code Playgroud)

反冲用于转义特殊字符。因此,在字符串文字中,反冲本身必须像这样转义。

"This is a single backlash: \\"
Run Code Online (Sandbox Code Playgroud)

不过,如果您希望字符串与键入的字符串完全相同,请使用 r 字符串。

r"arst \'{}\' arst"
Run Code Online (Sandbox Code Playgroud)