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

4

在Python 3.6中,如果想要在格式化字符串的结果中包含一个反斜杠,请注意#1和#2会产生相同的不良结果,但#3会导致太多的反斜杠,另一个不良结果。

2

在Python 3.6中,如果想在格式化字符串的结果中包含一对反斜杠,请注意 #1 和 #2 会产生相同的不良结果,但是 #3 会导致过多的反斜杠,这也是我们不想要的结果。

t = "arst '{}' arst"
t.format(d)
>> "arst '2017-34-12' arst"

2

t = "arst \'{}\' arst"
t.format(d)
>> "arst '2017-34-12' arst"

3

t = "arst \\'{}\\' arst"
t.format(d)
>> "arst \\'2017-34-12\\' arst"

我希望您能够提供以下最终结果:

我期望的最终结果如下:

>> "arst \'2017-34-12\' arst"

1
第三个是你想要的。你正在看到结果的 repr(),它显示了你需要在 Python 中键入的字符串,包括转义字符。实际的字符串只包含一个反斜杠,你可以通过 print(t.format(d)) 看到。 - kindall
"both one and two are already escaped. If you want to see it literally, then you must include both apostrophes eg. "arst '{}' arst,\"you said\"".format(d). Since this has a mixture of both 'and"then escape is necessary. If all the inside are'while the outside are"` then there will be no need of escaping. Also if you all of them are the same, then it will converse one to the other so as it might be readable." - Onyambu
3个回答

4
您的第三个例子是正确的。您可以使用print命令来确认它。
>>> print(t.format(d))
arst \'2017-34-12\' arst

你在控制台看到的实际上是字符串的表示形式。你可以使用repr获得它。

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

反斜杠用于转义特殊字符。因此,在字符串字面值中,反斜杠本身必须像这样进行转义。

"This is a single backlash: \\"

如果您希望字符串与输入的内容完全一致,可以使用原始字符串。

r"arst \'{}\' arst"

1
在字符串前面加上 'r' 表示将其声明为字符串字面值。
t = r"arst \'{}\' arst"

0
你被输出结果误导了。请参考:在Python字符串字面值中引用反斜杠
In [8]: t = "arst \\'{}\\' arst"

In [9]: t
Out[9]: "arst \\'{}\\' arst"

In [10]: print(t)
arst \'{}\' arst

In [11]: print(t.format('21-1-2'))
arst \'21-1-2\' arst

In [12]: 

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接