TAGS :Viewed: 10 - Published at: a few seconds ago

[ Why is the following string literal allowed? ]

Generating different combination of strings while working on some issue, observe the following behavior

In [3]: str = 'abcd'

In [4]: str
Out[4]: 'abcd'

In [5]: str = 'ab'cd'
------------------------------------------------------------
   File "<ipython console>", line 1
     str = 'ab'cd'
              ^
SyntaxError: invalid syntax


In [6]: str = 'ab''cd'

In [7]: str
Out[7]: 'abcd'

I'm aware of the condition where single quoted string can hold double quotes in between, and double quoted string can hold single quote in between.

Can someone please explain, why we are observing this behavior, where inside single quoted string two simultaneous single quotes are allowed, but single quote not.

Answer 1


Python implicitly concatenates nearby strings with nothing in between them. Observe:

>>> 'hel'  'lo'
'hello'
>>> 'cat'        'egory'
'category'
>>> 'ab''cd'
'abcd'

Strings with an odd number of one kind of quote are ambiguous and therefore not allowed.

>>> 'ab'cd'   # Here `cd` is a bareword and ' starts an unterminated string
  File "<stdin>", line 1
    'ab'cd'
         ^
SyntaxError: invalid syntax
>>> 'ab\'cd'  # The middle single quote is escaped so this is OK
"ab'cd"

This can be a sort of "gotcha" when dealing with lists if you forget a comma:

>>> ['a', 'b', 'c' 'd', 'e']  # no comma between 'c' and 'd'
['a', 'b', 'cd', 'e']