Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to use triple single quotes instead of triple double quotes

Tags:

python

quotes

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?

like image 765
0101amt Avatar asked Oct 16 '11 08:10

0101amt


People also ask

When would you wrap a string in triple single quotes or triple double quotes?

To create strings that span multiple lines, triple single quotes ''' or triple double quotes """ are used to enclose the string. ''' This string is on multiple lines within three single quotes on either side. ''' """ This string is on multiple lines within three double quotes on either side.

In what instances would you use triple quotes instead of single or double quotes when defining a string in Python?

Spanning strings over multiple lines can be done using python's triple quotes. It can also be used for long comments in code. Special characters like TABs, verbatim or NEWLINEs can also be used within the triple quotes. As the name suggests its syntax consists of three consecutive single or double-quotes.

What does Triple single quote mean?

Python's triple quotes comes to the rescue by allowing strings to span multiple lines, including verbatim NEWLINEs, TABs, and any other special characters. The syntax for triple quotes consists of three consecutive single or double quotes.


1 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.

like image 108
Mark Byers Avatar answered Sep 18 '22 13:09

Mark Byers