单引号字符串与双引号字符串 [英] Single quoted string vs. double quoted string
本文介绍了单引号字符串与双引号字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为什么单引号字符串需要转义字符,而双引号字符串则不需要转义字符?
Why do we need an escape character for single quoted string, but not for a double quoted string?
a = 'hello how\'s it going'
a1 = 'hello how's it going'
b = "hello how's it going"
assert(a==b) # Passes
assert(a1==b) # Errors
错误消息:
File "string.py", line 1
a = 'hello how's it going'
^
SyntaxError: invalid syntax
推荐答案
使用没关系'
或
将其标记为字符串文字,但是您不能在字符串文字中使用该字符,除非使用 \
在它前面-否则Python会将其解释为字符串的结尾。
It doesn't matter if you use '
or "
around the string to mark it as string literal. But you can't use that character inside the string literal without escaping it using a \
in front of it - otherwise Python interprets it as the end of the string.
例如<$在
分隔的字符串文字内的c $ c> c>也需要转义:
For example "
inside a "
delimited string literal need to be escaped as well:
a = "And he said: \"What a nice day\"."
这篇关于单引号字符串与双引号字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文