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?
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.
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.
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.
You can split a string by backslash using a. split('\\') .
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 "\"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With