Single and Double quotes in python strings
Strings in python can (and can only) be enclosed by pair single quotes, double quotes, and three double quotes (document strings:
'This is a book'
"This is a book"
"This is a book """
Strings enclosed by single quotation marks can contain double quotation marks, three quotation marks, and so on, but cannot contain single quotation marks (escape required)
'This is a "book'
'This is a "" book'
'This is a "book'
'This is a \ 'book'
You can also escape double quotation marks in multiple single quotes, but it is usually unnecessary and meaningless.
'This is a \ "book'
Similarly, double quotation marks can contain single quotes, but cannot contain double quotation marks and three quotation marks consisting of double quotation marks.
"This is a 'book"
"This is a \" book"
You can also escape single quotes in double quotes. However, this is usually unnecessary and meaningless.
"This is a \ 'book"
There is another question. If I want to display "\" in the string enclosed by single quotes, the answer is to escape "\" and "'" respectively, that is to say, to display the special character "\" in a string, escape the special character itself. Other special characters are similar.
>>> S = 'this is a \ 'book'
>>> Print s
This is a 'book
>>> S = 'this is a \\\ 'book'
>>> Print s
This is a \ 'book
How many escape operations are required for "\" to be displayed:
>>> S = 'this is a \\\\ 'book'
>>> Print s
This is a \ 'book
Similarly, to display "\" "in a string enclosed by double quotation marks, escape" \ "and" respectively.
>>> S = "this is a \\\" book"
>>> Print s
This is a \ "book
Here, it is necessary to talk about the replacement of "\" and "\" in the string, that is, the string itself contains such a substring, for example:
>>> S = 'this is a \\\ 'book'
>>> S
"This is a \ 'book"
>>> Print s
This is a \ 'book
The string here contains a substring such as "\". Now I want to replace it with "@"
>>> S = s. replace ('\\\'','@@@')
>>> S
'This is a @ book'
>>> Print s
This is a @ book
That is, when writing a substring to be replaced, special characters must also be escaped, s = s. after escaping in replace ('\ '',' @ '), the substring to be replaced is \' in the final string.
The replacement of substrings containing special characters in double quotes follows the same principle.
In addition, you should use the print function to print the final appearance of the string to avoid confusion.
>>> S = 'this is a \\\ 'book'
>>> S
"This is a \ 'book"
>>> Print s
This is a \ 'book
The single and double quotes in the above python strings are all the content shared by the editor. I hope you can give us a reference and support the help house.