47

Learn Python the hard way, exercise 10.2:

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

fat_cat = """
I'll do a list:
\t* Cat food
\t* Fishies
\t* Catnip\n\t* 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?

0101amt
  • 2,438
  • 3
  • 23
  • 21
  • 2
    look at http://stackoverflow.com/questions/56011/single-quotes-vs-double-quotes-in-python – spicavigo Oct 16 '11 at 08:14
  • in addition you don't have to remember the difference between `"` and `'` in python – Ruggero Turra Oct 16 '11 at 08:25
  • 1
    Can you see why you might use `'` instead of `"` or vice-versa? Try applying the same logic. – Karl Knechtel Oct 16 '11 at 09:26
  • I believe what the textbook author is driving at is how """ might look like '''''', depending on the text editor you are using. It may be more universally visually pleasing to use ''' instead of """. Functionally, there is no difference. – James Bender Oct 21 '22 at 16:06

2 Answers2

82

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.

Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
3

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'""")
wei
  • 4,267
  • 2
  • 23
  • 18