It pains me to ask this, but, for some reason I have not been able to get this to work (it's late in the day, yes, that's my excuse).
Let's say I have this string:
s = "John's book."
Using the replace
method from the object String, I want to turn it into this:
s = "John\'s book."
I would have expected this code to give me what I want:
s = s.Replace("'", "\\'")
But, that results in:
"John\\'s book."
It's done by finishing an already-opened one ( ' ), placing the escaped one ( \' ), and then opening another one ( ' ). It's done by finishing already opened one ( ' ), placing a quote in another quote ( "'" ), and then opening another one ( ' ).
Enclosing Quotation Marks That means strings containing single quotes need to use double quotes and strings containing double quotes need to use single quotes. "It's six o'clock."; 'Remember to say "please" and "thank you."'; Alternatively, you can use a backslash \ to escape the quotation marks.
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.
A single quote is not used where there is already a quoted string. So you can overcome this issue by using a backslash following the single quote. Here the backslash and a quote are used in the “don't” word. The whole string is accompanied by the '$' sign at the start of the declaration of the variable.
Do this so you don't have to think about it:
s = s.Replace("'", @"\'");
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