Reputation: 6748
In[1] : '\"""'
Out[1]: '"""'
In[2] : "\""""
Out[2]: '"'
In the following examples (in which I'm using python 3), why does changing the type of quote used to enclose a string change the actual value of the string? I'd expect "\""""=='\"""'
to be true, but it's false. And why does the second example return only a single double quote? Thanks!
Upvotes: 1
Views: 147
Reputation: 73
The single quote can end only with an other single quote,
hence '\"
is not a string and python then waits for the other '
to finish the string
so '\"""'
is one string and "\""""
is two strings, "\""
and ""
the results are then """
because python has to take \"""
in the string object, whereas the other is just a " with an empty string concatenated
I hope my answer is clear, it is not easy to explain with all these quotation marks
Upvotes: 1
Reputation: 1160
In[2] is actually two adjacent strings, similar to "foo""bar"
.
"\""""
contains a first string "\""
and a second string ""
.
When evaluating that, Python concatenates them:
In[1]: "foo""bar"
Out[1]: 'foobar'
In your case, since the 2nd string is empty, you just get the first.
Upvotes: 1
Reputation: 24681
Python does something the same way C does, in terms of string concatenation:
'hello' 'world' == 'helloworld'
That is, if you put two quoted string literals next to each other, with nothing in between, they will be concatenated together. This is the difference between 1
and 2
:
In[2] : "\"""" --> "\"" ""
So your second input is actually concatenating the string "
with an empty string.
Upvotes: 1
Reputation: 530922
The expression "\""""
is two string literals, "\""
and ""
(or '"'
and ''
, switching to single quotes for clarity), concatenated together. The double-quoted equivalent of '\"""'
would be "\"\"\""
.
>>> ("\""
... ""
... )
'"'
>>> "\"\"\""
'"""'
Upvotes: 3