Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Quoting backslashes in Python string literals [duplicate]

Tags:

python

string

I have a string that contains both double-quotes and backslashes that I want to set to a variable in Python. However, whenever I try to set it, the quotes or slashes are either removed or escaped. Here's an example:

>>> foo = 'baz "\"' >>> foo 'baz ""' 

So instead of baz "\" like I want I'm getting baz "". If I then try to escape the backslash, it doesn't help either:

>>> foo = 'baz "\\"' >>> foo 'baz "\\"' 

Which now matches what I put in but wasn't what I originally wanted. How do you get around this problem?

like image 258
Chris Bunch Avatar asked Nov 19 '08 05:11

Chris Bunch


People also ask

Why is Python adding backslashes to string?

In Python strings, the backslash "\" is a special character, also called the "escape" character. It is used in representing certain whitespace characters: "\t" is a tab, "\n" is a newline, and "\r" is a carriage return. Conversely, prefixing a special character with "\" turns it into an ordinary character.

How do you pass a slash in a string in Python?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

How do you replace a backslash in a string Python?

We can use the replace() function to replace the backslashes in a string with another character. To replace all backslashes in a string, we can use the replace() function as shown in the following Python code.

How do you split a string with a backslash in Python?

You can split a string by backslash using a. split('\\') .


1 Answers

You're being mislead by output -- the second approach you're taking actually does what you want, you just aren't believing it. :)

>>> foo = 'baz "\\"' >>> foo 'baz "\\"' >>> print(foo) baz "\" 

Incidentally, there's another string form which might be a bit clearer:

>>> print(r'baz "\"') baz "\" 
like image 125
Charles Duffy Avatar answered Sep 17 '22 16:09

Charles Duffy