Sadık
Sadık

Reputation: 4419

backslashes in strings

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?

Upvotes: 1

Views: 86

Answers (3)

tmt
tmt

Reputation: 103

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)

Upvotes: 0

Jean-François Fabre
Jean-François Fabre

Reputation: 140307

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?"

Upvotes: 5

Adrian B
Adrian B

Reputation: 1630

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!"

Upvotes: 1

Related Questions