2

I thought I knew what the different types of Python quotations mean, but got a little confused by this example:

my_string = 'the cat sat on the mat' 
my_string = "the cat sat on the mat" 
my_string = """the cat sat on the mat""" 
my_string = '''the cat sat on the mat'''

The first two seem to be two different ways of declaring a string using single or double quotes. The last two seem to be comments that leave the expressions incomplete (and will generate an error in the interpreter. Is this right?

MNRC
  • 175
  • 2
  • 12

2 Answers2

5

The last two are not comments , they are multi-line strings, If you print out the last two strings you will see that you get output on the console.

my_string3 = """the cat sat on the mat"""

print my_string3
>>> the cat sat on the mat

If """...""" denoted a comment then you must have received an error message while initializing such variable as a = #dad would raise an error.

As the strings initialized with """ are multi-line so we can initialize some strings as:

my_string3 = """the
cat sat on 
the mat""" 

print my_string3
>>> the
    cat sat on 
    the mat
ZdaR
  • 22,343
  • 7
  • 66
  • 87
  • Is this the same for both ''' and """? – MNRC Jun 03 '15 at 06:49
  • 1
    `"..."` and `'...'` are same as both are used to declare single line strings, `"""..."""` and `'''...'''` are same as both are used to declare multi-line comments. – ZdaR Jun 03 '15 at 06:51
1

Examples:

text1 = "This is s single-line text with doubles"
text2 = 'This is s single-line text too but with singles'
text3 = "FallenAngel'S text should have doubles since there is an apostrophe in the string and signles would cause problems"

text4 = """This is a
        multi line string, and the output would be multi-line too"""
text5 = '''This is another multi-line.
        Both multi-lines generally used in writing Sql Query strings
        and this style makes them more readable'''
text6 = """Single line triple quotes are ok, but they do not look much useful"""
text7 = '''This is ok too, but as I said, it is not common and not pretty.'''

def somefunc():
    """And this is a doc-string. Python advice using triple double quotes in doc-strings even if they are single line"""
    pass
Mp0int
  • 18,172
  • 15
  • 83
  • 114