Using quotation marks inside quotation marks
When I want to do a print
command in Python and I need to use quotation marks, I don't know how to do it without closing the string.
For instance:
print " "a word that needs quotation marks" "
But when I try to do what I did above, I end up closing the string and I can't put the word I need between quotation marks.
How can I do that?
You could do this in one of three ways:
-
Use single and double quotes together:
print('"A word that needs quotation marks"') "A word that needs quotation marks"
-
Escape the double quotes within the string:
print("\"A word that needs quotation marks\"") "A word that needs quotation marks"
-
Use triple-quoted strings:
print(""" "A word that needs quotation marks" """) "A word that needs quotation marks"
You need to escape it. (Using Python 3 print function):
>>> print("The boy said \"Hello!\" to the girl")
The boy said "Hello!" to the girl
>>> print('Her name\'s Jenny.')
Her name's Jenny.
See the python page for string literals.
Python accepts both " and ' as quote marks, so you could do this as:
>>> print '"A word that needs quotation marks"'
"A word that needs quotation marks"
Alternatively, just escape the inner "s
>>> print "\"A word that needs quotation marks\""
"A word that needs quotation marks"
Use the literal escape character \
print("Here is, \"a quote\"")
The character basically means ignore the semantic context of my next charcter, and deal with it in its literal sense.