在处理某些问题时生成不同的字符串组合, 观察以下行为
In [3]: str = 'abcd'
In [4]: str
Out[4]: 'abcd'
In [5]: str = 'ab'cd'
------------------------------------------------------------
File "<ipython console>", line 1
str = 'ab'cd'
^
SyntaxError: invalid syntax
In [6]: str = 'ab''cd'
In [7]: str
Out[7]: 'abcd'
我知道单引号字符串可以包含双引号,双引号字符串可以包含单引号。
有人可以解释一下,为什么我们会观察到这种行为,在单引号字符串中允许同时使用两个单引号,但不允许使用单引号。
请您参考如下方法:
Python 隐式连接附近的字符串,它们之间没有任何内容。观察:
>>> 'hel' 'lo'
'hello'
>>> 'cat' 'egory'
'category'
>>> 'ab''cd'
'abcd'
具有奇数个引号的字符串是不明确的,因此是不允许的。
>>> 'ab'cd' # Here `cd` is a bareword and ' starts an unterminated string
File "<stdin>", line 1
'ab'cd'
^
SyntaxError: invalid syntax
>>> 'ab\'cd' # The middle single quote is escaped so this is OK
"ab'cd"
如果您忘记逗号,这可能是处理列表时的一种“陷阱”:
>>> ['a', 'b', 'c' 'd', 'e'] # no comma between 'c' and 'd'
['a', 'b', 'cd', 'e']
