How To Print Single or Double Quotes With Python

When printing strings with Python, we might need to print single (‘) or double quote (“) as part of the string.

Escapeing

Python call that process escaping, and it allows us to print a sequence of characters inside a string without breaking the code. Let review the following code.

mystring = "This is a "test" "

The above code will not pass and will throw an error. To bypass this issue, we can escape that the double quote as shown below.

mystring = "This is a \"test\" "
print (mystring)

To escape a single quote (‘), I would use the following example.

mystring3 = 'This is a \'test\' '
print (mystring3)

Triple quote

Another option that allows up to escape double or single quotes is to use triple quotes (“””) as show below.

mystring4 = """  this is a "test" and another 'test'  """
print (mystring4)

Leave a comment

Your email address will not be published. Required fields are marked *