[python] 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?

This question is related to python string python-2.7

The answer is


I'm surprised nobody has mentioned explicit conversion flag yet

>>> print('{!r}'.format('a word that needs quotation marks'))
'a word that needs quotation marks'

The flag !r is a shorthand of the repr() built-in function1. It is used to print the object representation object.__repr__() instead of object.__str__().

There is an interesting side-effect though:

>>> print("{!r} \t {!r} \t {!r} \t {!r}".format("Buzz'", 'Buzz"', "Buzz", 'Buzz'))
"Buzz'"      'Buzz"'     'Buzz'      'Buzz'

Notice how different composition of quotation marks are handled differenty so that it fits a valid string representation of a Python object 2.


1 Correct me if anybody knows otherwise.

2 The question's original example " "word" " is not a valid representation in Python


One case which is prevalent in duplicates is the requirement to use quotes for external processes. A workaround for that is to not use a shell, which removes the requirement for one level of quoting.

os.system("""awk '/foo/ { print "bar" }' %""" % filename)

can usefully be replaced with

subprocess.call(['awk', '/foo/ { print "bar" }', filename])

(which also fixes the bug that shell metacharacters in filename would need to be escaped from the shell, which the original code failed to do; but without a shell, no need for that).

Of course, in the vast majority of cases, you don't want or need an external process at all.

with open(filename) as fh:
    for line in fh:
        if 'foo' in line:
            print("bar")

in Python 3.2.2 on Windows,

print(""""A word that needs quotation marks" """) 

is ok. I think it is the enhancement of Python interpretor.


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.


When you have several words like this which you want to concatenate in a string, I recommend using format or f-strings which increase readability dramatically (in my opinion).

To give an example:

s = "a word that needs quotation marks"
s2 = "another word"

Now you can do

print('"{}" and "{}"'.format(s, s2))

which will print

"a word that needs quotation marks" and "another word"

As of Python 3.6 you can use:

print(f'"{s}" and "{s2}"')

yielding the same output.


You could also try string addition: print " "+'"'+'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.


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"

This worked for me in IDLE Python 3.8.2

print('''"A word with quotation marks"''')

Triple single quotes seem to allow you to include your double quotes as part of the string.


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to python-2.7

Numpy, multiply array with scalar Not able to install Python packages [SSL: TLSV1_ALERT_PROTOCOL_VERSION] How to create a new text file using Python Could not find a version that satisfies the requirement tensorflow Python: Pandas pd.read_excel giving ImportError: Install xlrd >= 0.9.0 for Excel support Display/Print one column from a DataFrame of Series in Pandas How to calculate 1st and 3rd quartiles? How can I read pdf in python? How to completely uninstall python 2.7.13 on Ubuntu 16.04 Check key exist in python dict