字符串创建:两个语法"和"之间的差异?

NIl*_*rma 2 python string syntax

可能重复:
Python中的单引号与双引号

通常我们代表,创建这样的字符串

 s = 'abc'
Run Code Online (Sandbox Code Playgroud)

也喜欢这个

 c = "abc"
Run Code Online (Sandbox Code Playgroud)

理想情况下两种方式都相同,而不是为什么我们有两种语法来做同样的事情?这两者之间是否存在差异,或者理想情况下它们是相同的.

Mar*_*ers 9

基本上是相同的,除了你必须逃脱的东西:

"'"
'"'
Run Code Online (Sandbox Code Playgroud)

两者都有效,但要合并多个引用类型,必须转义用于创建字符串的类型:

"\"'"
'"\''
Run Code Online (Sandbox Code Playgroud)

这两个存在是为了让您轻松避免不得不逃避您的报价,所以以下两个很容易:

'She said: "Not so fast!"'
"Won't you come with us?"
Run Code Online (Sandbox Code Playgroud)

请注意,还有tripple-quote变体:

"""Now I can use either quote with more freedom: ' and "."""
'''Now I can use either quote with more freedom: ' and ".'''
Run Code Online (Sandbox Code Playgroud)

这些也允许包含新行而不转义:

"""A
multiline
string
is
easy.
"""
Run Code Online (Sandbox Code Playgroud)

最后一个例子要求你使用过多的\n转义序列.