Quotes within quotes

329 views Asked by At

In Python 3.x:

    print(""s"")       # SyntaxError
    print("""s""")     # prints s
    print(""""s"""")   # SyntaxError
    print("""""s""""") # prints ""s

What is the reason behind this different behaviour, when there are different numbers of double quotes in the string?

3

There are 3 answers

0
thefourtheye On BEST ANSWER

In Python you can create multiline strings with """...""". Quoting the documentation for strings,

String literals can span multiple lines. One way is using triple-quotes: """...""" or '''...'''.

In your first case, ""s"" is parsed like this

"" (empty string literal)  s  "" (empty string literal)

Now, Python doesn't know what to do with s. That is why it is failing with SyntaxError.

In your third case, the string is parsed like this

"""  "s  """ (End of multiline string)  `"`

Now the last " has no matching ". That is why it is failing.

In the last case, """""s""""" is parsed like this

"""  ""s  """  ""

So, the multiline string is parsed successfully and then you have an empty string literal next to it. In Python, you can concatenate two string literals, by writing them next to each other, like this

print ("a" "b")
# ab

So, the last empty string literal is concatenated with the ""s.

0
Ulrich Eckhardt On

The string literal concatenation rules inherited from C are responsible for that. Consider this:

x = "a" "b"

The two strings are joined into one, according to Python syntax.

Another aspect of this is that triple-quoted strings (intended for multiline strings like doc strings) also exist, which further complicate the issue. There, a beginning triple-quote is matched by the next triple quote.

Now, consider your cases is that light and group every double quotes or triple quotes. You will find that in one case you have a single token s in the middle, sometimes the s is part of a string, sometimes there are leftover quotes at the end etc.

0
jonrsharpe On

There are two things you need to know to understand this:

  1. As well as regular strings "foo" Python has multiline strings, which open and close with three quotes """foo""" (see String Literals); and
  2. Consecutive string literals are concatenated "foo" "bar" == "foobar" (see String Literal Concatenation).

As for your four examples:

""s""

closes the single quote before the s appears, so is equivalent to:

x = ""
x s x

which obviously makes no sense.

"""s"""

is a multiline string with a single character in.

""""s""""

is a multiline string containing two characters ("s) followed by a single unmatched quote.

"""""s"""""

is a multiline string containing three characters (""s) concatenated to an empty string literal.