When to use single vs double quotes?

Question

In the context of this exercise which introduces strings, when should single or double quotes be used for a string?

Answer

Typically, either single or double quotes can be used interchangeably for creating a string. However, in certain situations, the type of quotes can matter, depending on the content of the string itself. If the string contains single quotes, it can be more convenient to wrap the entire string in double quotes. And if the string contains double quotes, you might use single quotes to wrap the string instead.

The reason for this is that each string starts and ends when a pair of quotes is encountered. If there is another matching quote within the string, that may end the string prematurely, causing errors.

# Examples of valid strings
print("I'm coding!")
print('The computer printed the string "Hello!"')

# Example of invalid string 
print("A common phrase in programming is "Hello world"")
63 Likes

There is no difference unless you have words like (It’s, they’re, etc…)
but you can always use '.

# EXAMPLE

# the following two lines print Hello World! to the screen
print('Hello World!')
print("Hello World")

# the following two lines prints It's a sunny day
print('It\'s a sunny day')
print("It's a sunny day")
30 Likes

What if you had to use two types of quotes inside of a string? For instance if I wrote (example: Bobbi told me, “Delia said, ‘This will never work.’ ”)?

3 Likes

Well, you could use triple-quotes, but that would (IMHO) be a misuse of triple-quotes. I think that the Pythonic solution would be to escape (backslash) the double-quotes:

print(""" "Delia said, 'This will never work.' " """)  # works, but ugly

print(" \"Delia said, 'This will never work.' \" ")   # better, I think

Output:

 "Delia said, 'This will never work.' " 
 "Delia said, 'This will never work.' " 
16 Likes

I did’t get it at first, and thank you so much. To be honest this Codecademy thing is actually quite moving

9 Likes

what is the difference between a double and a single quoted string.

In Python, there’s no difference.

1 Like

Thank you, I did not know that using “” or ’ made a difference with special characters.