How do you escape a double quote in python?
How do I replace " with \" in a python string? Show I have a string with double quotes:
I want to escape the double quotes with one backslash. Doing the following doesn't quite work, it escapes with two backslashes:
Printing the output of that string shows what I want. But I don't just want to print the correct string, I want it saved in a variable. Can anyone help me with the correct magical regular expression? asked Jun 23, 2011 at 19:47
Your original attempt works just fine. The double backslashes you see are simply a way of displaying the single backslashes that are actually in the string. See also:
answered Jun 23, 2011 at 20:00
ʇsәɹoɈʇsәɹoɈ 21.6k7 gold badges52 silver badges59 bronze badges The string is correct. But Note that this is a rather limited escaping algorithm. Depending on what you need it for, you may have to expand it significantly (or there's a ready-made solution, e.g. preprared statements when working with databases) answered Jun 23, 2011 at 19:52 This did the job for me.
answered Mar 27, 2017 at 12:04
dinadina 7721 gold badge11 silver badges26 bronze badges one backslash cannot be seen, but the backslash remains in the string. if you will check the length of same string you will able to see answer. Also, if you will replace new string again with double quotes, you will get original string. answered Jun 24, 2011 at 5:10
samsam 17.5k24 gold badges77 silver badges114 bronze badges The other answers can be dangerous and failFor example:
Here is a better solution
BUT This doesn't escape everything. It should only ensure that double-quotes are always escaped. To escape
everything for python, try using
answered Jun 29 at 13:29
Jeff HykinJeff Hykin 1,29113 silver badges23 bronze badges How do you handle double quotes in Python?Escape from single quote in a string in Python
So we need to escape from this single quote. Solutions: Put the string in between double quotes instead of single quotes. Put the escaping character before the single quote in the string.
How do you escape a quote in Python?You can put a backslash character followed by a quote ( \" or \' ). This is called an escape sequence and Python will remove the backslash, and put just the quote in the string. Here is an example. The backslashes protect the quotes, but are not printed.
How do you escape a double quote?If you need to use the double quote inside the string, you can use the backslash character. Notice how the backslash in the second line is used to escape the double quote characters. And the single quote can be used without a backslash.
How do you ignore a double quote in a string?To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll("^\"|\"$", ""); After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.
|