4

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"
Community
  • 1
  • 1
vaer-k
  • 10,923
  • 11
  • 42
  • 59
  • 1
    The third is what you want. You're seeing the `repr()` of the result, which shows what you'd need to type back into Python to get that string, including escapes. The actual string contains only a single backslash, as you can see via `print(t.format(d))`. – kindall Aug 22 '18 at 01:11
  • 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 Aug 22 '18 at 01:19

3 Answers3

4

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"
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
1

Put a 'r' in front of your string to declare it as a string literal

t = r"arst \'{}\' arst"
vividpk21
  • 384
  • 1
  • 11
0

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]: 
Tom W
  • 31
  • 2