0

When using (or not using) an escape backslash before a single quote when printing a plain string in Python,

print("\"Sari\'s here,\" I said.")
print("\"Sari's here,\" I said.")

both work as expected, producing

>>>"Sari's here," I said.
>>>"Sari's here," I said.

However, putting the same string into a container (list, tuple, or dictionary) and printing it causes some behavior that I don't understand.

print(["Sari's here, I said."])
print(["Sari\'s here, I said."])
print(["\"Sari's here,\" I said."])
print(["\"Sari\'s here,\" I said."])
print(["\"Sari\\'s here,\" I said."])

>>>["Sari's here, I said."]
>>>["Sari's here, I said."]
>>>['"Sari\'s here," I said.']
>>>['"Sari\'s here," I said.']
>>>['"Sari\\\'s here," I said.']

The backslash is printed before a single quote (whether I put it there or not) if I use an escape before a double quote. If I put two backslashes before the single quote, I get a third.

Can someone please help me to make sense of this? My original implementation was for height value in a dictionary (using a single and a double quote for feet and inches), when I discovered this strange behavior.

Please be kind. I'm learning the basics, but I'm eager.

  • I don't know the reason behind it, but I just discovered that while printing the whole container produced the artifact, printing the index produces the beautiful text I was looking for. – JuicyJustin Nov 20 '20 at 03:53
  • Yes, @Macattack, that makes a lot of sense. The string in a container is favoring the unambiguous __repr__ form, rather than the more readable __str__ form to avoid confusion. Do I have that right? – JuicyJustin Nov 20 '20 at 04:04
  • Clarification - the "container" is a list containing a single element (`list()`). In order to print something, it has to be a string. If it isn't already a string, then print would call `str()` on it. Objects get to chose what they do when asked to make a string, by defining `__str__` function. When you print the string, it's not necessary for anything to be done because it's already a string. When you print the list, it has to make itself into a string, so it choses to take the `repr()` of each of its elements. Example: https://gist.github.com/macboy012/7a1704f8ae372aa0e97648beac4d9181 – Macattack Nov 20 '20 at 20:55

0 Answers0