When to use triple single quotes instead of triple double quotes
Asked Answered
B

2

49

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?

Burthen answered 16/10, 2011 at 8:10 Comment(4)
look at #56511X
in addition you don't have to remember the difference between " and ' in pythonMarcelmarcela
Can you see why you might use ' instead of " or vice-versa? Try applying the same logic.Jedediah
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.Varner
P
84

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.

Phosphoroscope answered 16/10, 2011 at 8:14 Comment(0)
B
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'""")
Broomfield answered 2/11, 2020 at 4:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.