Single quoted string vs. double quoted string

最后都变了- 提交于 2019-12-06 08:04:38

问题


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

The error message:

 File "string.py", line 1
    a = 'hello how's it going'
                  ^
SyntaxError: invalid syntax

回答1:


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.

For example " inside a " delimited string literal need to be escaped as well:

a = "And he said: \"What a nice day\"."



回答2:


Because the single quote closes the string. For example

'Broken' single quote string'
"Broken" double quote string"

If you need a single quote in a string use double quotes, and vice versa

"valid 'single' quote in a string"
'valid "double" quote in a string'



回答3:


You can use single or double quotes, but if you want to use them inside a string without scaping them, the opening and closing symbols should be different from those using inside the string.

For example, you could do:

a = "hello how's it going"

Or:

a = 'hello my "friend"'



回答4:


Single Quote

When you start the string with single quote ', then it searches for the next single quote ' to end the string. When it encounters the second single quote ' it end the string with that quote and beyond that second quote it does not accept anything as a string. So you need to put the quote with the backslash as an escape character.

Double Quote

As you might have guessed, in this case also string starts and ends with double quotes ". Between the first double quote and second double quote, it accepts anything as a string except a double quote (reason same as in the case of single quote).

Hope this clarifies your concept of strings:)



来源:https://stackoverflow.com/questions/45999335/single-quoted-string-vs-double-quoted-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!