简体   繁体   中英

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

The error message:

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

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\"."

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'

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"'

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:)

The choice between both the types (single quotes and double quotes) depends on the programmer's choice. Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it's sometimes our need to use one type over the other.

Read more

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM