Single and double arguments in the python string

  • 2020-05-26 09:27:00
  • OfStack

Strings in python can (and only can) be surrounded by pairs of single quotes, double quotes, and three double quotes (docstrings) :

'this is a book'
"this is a book"
"""this is a book"""

You can include double quotation marks, 3 quotation marks, etc. in strings surrounded by single quotation marks, but you cannot include single quotation marks themselves (escaped)

'this is a" book'
'this is a"" book'
'this is a""" book'
'this is a\' book'

Double quotation marks in multiple single quotation marks can also be escaped, but they are usually unnecessary and meaningless, right

'this is a\" book'

Similarly, double quotation marks can contain single quotation marks, but not double quotation marks and 3 quotation marks made of double quotation marks

"this is a' book"
"this is a\" book"

It is also possible to escape single quotes within double quotes, but again, this is usually unnecessary and meaningless

"this is a\' book"

Now, one more question, if I want to show "\" in a string surrounded by single quotes, the answer is to escape "\" and "'" respectively, that is, to show the special character "\" in a string, I need to 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 times to escape "\" to show "\" :

> > > s='this is a\\\\\' book'
> > > print s
this is a\\' book


Similarly, to display "\" in a string surrounded by double quotes, escape" \" and "", respectively.

> > > s="this is a\\\" book"
> > > print s
this is a\" book

Speaking of which, it is necessary to talk about 1 about the substitution of "\'" and "\" in the string, that is, the string itself contains such a substring, such as:

> > > s='this is a\\\' book'
> > > s
"this is a\\' book"
> > > print s
this is a\' book


The string here contains a substring like "\'", and now I want to replace this substring with "@@@".
> > > s=s.replace('\\\'','@@@')
> > > s
'this is a@@@ book'
> > > print s
this is a@@@ book

In other words, when writing the substring to be replaced, special characters need to be escaped, s= s.replace ('\\\','@@@'), and the substring to be replaced in the final string will be "\'".

Substrings with special characters in double quotes follow the same principle.

It is also important to note that if you want to know what the string ends up looking like, you should print it out using the print function to avoid confusion.

> > > s='this is a\\\' book'
> > > s
"this is a\\' book"
> > > print s
this is a\' book


Related articles: