When to use triple single quotes instead of triple double quotes

Question:

Learn Python the hard way, exercise 10.2:

tabby_cat = "tI'm tabbed in."
persian_cat = "I'm splitnon a line."
backslash_cat = "I'm \ a \ cat."

fat_cat = """
I'll do a list:
t* Cat food
t* Fishies
t* Catnipnt* Grass
"""

print tabby_cat
print persian_cat
print backslash_cat
print fat_cat

2: Use ''' (triple-single-quote) instead. Can you see why you might use that instead of """?

I can’t see why I might use ''' instead of """. It gives me the same output. Can someone explain me why I would use triple-single-quote instead of triple-double-quote? What’s the difference between them?

Asked By: 0101amt

||

Answers:

The only reason you might need """ instead of ''' (or vice versa) is if the string itself contains a triple quote.

s1 = '''This string contains """ so use triple-single-quotes.'''
s2 = """This string contains ''' so use triple-double-quotes."""

If a string contains both triple-single-quotes and triple-double-quotes then you will have to escape one of them, but this is an extremely rare situation.

Answered By: Mark Byers

I found similar situations need ”’ instead of """ which is when a double quote symbol at the end of the string, vice versa.

Invalid syntaxes:

print("""2 feet 4 inches can be written in 2' 4"""")
print('''2 feet can be written in 2'''')

Valid syntaxes:

print('''2 feet 4 inches can be written in 2' 4"''')
print("""2 feet can be written in 2'""")
Answered By: wei
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.