简体   繁体   English

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

[英]How do you escape a single backslash in a formatted python string?

Having some trouble including a single pair of backslashes in the result of a formatted string in Python 3.6. 在Python 3.6中格式化字符串的结果中包含一对反斜杠时遇到了一些麻烦。 Notice that #1 and #2 produce the same unwanted result, but #3 results in too many backslashes, another unwanted result. 请注意,#1和#2产生相同的不需要的结果,但是#3导致太多的反斜杠,这是另一个不需要的结果。

1 1

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

2 2

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

3 3

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

I'm looking for a final result that looks like this: 我正在寻找看起来像这样的最终结果:

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

Your third example is correct. 您的第三个例子是正确的。 You can print it to make sure of that. 您可以print以确保这一点。

>>> print(t.format(d))
arst \'2017-34-12\' arst

What you are seeing in your console is in fact the representation of the string. 实际上,您在控制台中看到的是字符串的表示形式。 You can indeed obtain it by using repr . 您确实可以使用repr获得它。

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

A backlash is used to escape a special character. 反冲用于转义特殊字符。 So in a string literal, a backlash must itself be escaped like so. 因此,在字符串文字中,必须自己避免反冲。

"This is a single backlash: \\"

Although if you want your string to be exactly as typed, use an r-string. 尽管如果希望您的字符串与键入的字符串完全相同,请使用r字符串。

r"arst \'{}\' arst"

在字符串前面放置一个“ r”以将其声明为字符串文字

t = r"arst \'{}\' arst"

You are being mislead by the output. 您被输出误导了。 See: Quoting backslashes in Python string literals 请参阅: 在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]: 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM