简体   繁体   中英

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. Notice that #1 and #2 produce the same unwanted result, but #3 results in too many backslashes, another unwanted result.

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"

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(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 .

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

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

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

You are being mislead by the output. See: Quoting backslashes in Python string literals

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]: 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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