1

When printinga a string containing a backslash, I expect the backslash (\) to stay untouched.

test1 = "This is a \ test String?"
print(test1)
'This is a \\ test String?'

test2 = "This is a '\' test String?"
print(test2)
"This is a '' test String?"

What I expect is "This is a \ test String!" or "This is a '\' test String!" respectively. How can I achieve that?

Sadık
  • 4,249
  • 7
  • 53
  • 89
  • 1
    If you `print` them (or write them to a file) the \ is escaped. – Shmack Jan 03 '23 at 15:16
  • 2
    The `.replace()` has NOTHING to do with this - if you just typed `test1` or `test2`, to display the `repr()` of the string value, you'd get exactly the same behavior of the backslash. – jasonharper Jan 03 '23 at 15:20
  • Does this answer your question? [Python prints two backslash instead of one](https://stackoverflow.com/questions/58639925/python-prints-two-backslash-instead-of-one) – user3840170 Jan 03 '23 at 15:37
  • What helped was the answer mentioning raw string. The question you posted doesn't have that. – Sadık Jan 04 '23 at 13:35

3 Answers3

5

Two issues.

First case, you're getting the representation not the string value. that's a classic explained for instance here: Python prints two backslash instead of one

Second case, you're escaping the quote unwillingly. Use raw string prefix in all cases (specially treacherous with Windows hardcoded paths where \test becomes <TAB>est):

test2 = r"This is a '\' test String?"

In the first case, it "works" because \ doesn't escape anything (for a complete list of escape sequences, check here), but I would not count too much on that in the general case. That raw prefix doesn't hurt either:

test1 = r"This is a \ test String?"
Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

You should add an extra backslash in your code before the replace:

test2 = "This is a '\\' test String?"
test2.replace("?", "!")
"This is a '\' test String!"
Adrian B
  • 1,490
  • 1
  • 19
  • 31
0

Python is actually doing what you expect - the confusion lies in the fact that you are using str.__repr__ to display the content of the string. If you print it, it looks ok:

In [17]: test1 = "This is a \ test String?"

[18]: test1
Out[18]: 'This is a \\ test String?'

In [19]: print(test1)
This is a \ test String?

Python shows the string with a double backslash as a single backslash wouldn't be an acceptable representation (i.e. it would mean you are escaping the character after the backslash)

tmt
  • 83
  • 4