A string in Python can (and can only) be surrounded with paired single quotes, double quotes, and three double quotation marks (document strings):
' This was a book '
"This was a book"
"" "This is a book" ""
A string enclosed in single quotation marks, including double quotes, three quotation marks, and so on, but cannot contain single quotes themselves (escaped)
' This was a ' book '
' This is a ', ' book '
' This is a ', ' "book '
' This was a\ ' book '
Double quotes can also be escaped in multiple single quotes, but usually not necessary and meaningful
' This was a\ ' book '
In the same vein, double quotation marks can contain single quotes, but cannot contain double quotes and three quotation marks consisting of double quotation marks
"This was a ' book"
"This was a\" book "
You can also escape single quotes in double quotes, but again, this is usually unnecessary and meaningless.
"This was A\ ' book"
Now there is another question, if I want to display "\" in a string surrounded by single quotes, the answer is to escape the "\" and "'" separately, that is, to display the "\" character in the string, you need to escape the special character itself, similar to other special characters.
>>> s= ' This was a\ ' book '
>>> Print S
This was a ' book
>>> s= ' This was a\\\ ' book '
>>> Print S
This was A\ ' book
To show how many times "\" is to be escaped for "\":
>>> s= ' This was a\\\\\ ' book '
>>> Print S
This was a\\ ' book
Similarly, to display "\" in a string surrounded by double quotes, you also want to escape "\" and "" separately.
>>> s= "This was a\\\" book "
>>> Print S
This was A\ "book
Speaking of which, it is necessary to talk about the substitution of "\" and "\" in the string, that is, the string itself contains such a substring, such as:
>>> s= ' This was a\\\ ' book '
>>> s
"This was a\\ ' book"
>>> Print S
This was A\ ' book
The string here contains a substring such as "\ '" And now wants to replace this substring with "@@@"
>>> s=s.replace (' \\\ ', ' @@@ ')
>>> s
' This was a@@@ book '
>>> Print S
This was a@@@ book
It is also necessary to escape a special character when writing a substring to be replaced, and the S=s.replace (' \\\ ', ' @@@ ') is escaped and the substring that is replaced in the final string is "\ '".
The substitution of substrings containing special characters in double quotes follows the same principle.
It is also important to note that if you want to know the final appearance of the string, you should print it out using the print function to avoid confusion.
>>> s= ' This was a\\\ ' book '
>>> s
"This was a\\ ' book"
>>> Print S
This was A\ ' book
Above this python string in the single and double cited is the small part of the whole content to share to everyone, I hope to give you a reference, but also hope that we have a lot of support topic.alibabacloud.com.