Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What difference does it make to surround string literals with multiple quotation marks?

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?

like image 516
Sanjana S Avatar asked Mar 17 '26 03:03

Sanjana S


2 Answers

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.

like image 99
thefourtheye Avatar answered Mar 18 '26 16:03

thefourtheye


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.

like image 23
jonrsharpe Avatar answered Mar 18 '26 17:03

jonrsharpe