Reputation: 33
I would like an output of Siti's father says, "Hello."
.
However, the closest I've gotten to is:
s = "Siti's father says, \"Hello\""
with s
being a variable to contain the required output.
The problem arises when I do print("Siti's father says, \"Hello\"")
and get the perfect output, but when I assign the the above text to a variable s
, I get a different output when defining s
. I get: 'Siti\'s father says, "Hello"'
What should I change to get the perfect output, assuming I can only use escape codes to get the desired output?
Upvotes: 0
Views: 785
Reputation: 522016
There's a difference between a string representation and the string's contents. Whenever you print
something, Python will output the string's content as is. Whenever you inspect a value (e.g. by just typing s
on the prompt, or using repr(s)
), Python will give you a representation of the value; it's trying to give you something that you can preferably use as is in Python source code. Example:
>>> datetime.now()
datetime.datetime(2018, 7, 13, 15, 58, 37, 162588)
You can use datetime.datetime(2018, 7, 13, 15, 58, 37, 162588)
literally like this in Python source code to recreate exactly this datetime
object.
With strings it works the same. The string literal "Siti's father says, \"Hello\""
creates a string with the content Siti's father says, "Hello"
. A representation of that string would be any of these:
"Siti's father says, \"Hello\""
'Siti\'s father says, "Hello"'
'''Siti's father says, "Hello"'''
'Siti\x27s father says, "Hello"'
Python gives you one of these possible representations, namely the single-quote delimited one.
Upvotes: 4
Reputation: 185
When you display a variable or directly enter a string into the Python shell, it will be wrapped in single quotes.
>>> "String"
'String'
Python escapes the single quote in your string when you display it because it's wrapped in single quotes. Otherwise, you would have something like this, and it would be unclear where the string ends:
'John's potato farm'
When you print it, it will appear with no quotes around it, as you would expect.
>>> s = "String"
>>> print(s)
String
To answer your question: create the string exactly as you're already doing it, and then print it out.
s = "Siti's father says, \"Hello.\""
print(s)
Upvotes: 4