簡體   English   中英

如何在格式化的python字符串中轉義單個反斜杠?

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

在Python 3.6中格式化字符串的結果中包含一對反斜杠時遇到了一些麻煩。 請注意,#1和#2產生相同的不需要的結果,但是#3導致太多的反斜杠,這是另一個不需要的結果。

1

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"

您的第三個例子是正確的。 您可以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字符串。

r"arst \'{}\' arst"

在字符串前面放置一個“ r”以將其聲明為字符串文字

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

您被輸出誤導了。 請參閱: 在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