pythonstringstring-literals

How to write a string literal containing both single and double quotes?


In Python how would I write the string '"['BOS']"'.

I tried entering "\"['BOS']\"" but this gives the output '"[\'BOS\']"' with added backslashes in front of the '.


Solution

  • You can use triple quotes:

    '''"['BOS']"'''
    

    What you did ("\"['BOS']\"") is fine too. You get the backslashes on output, but they aren't part of the string:

    >>> a = "\"['BOS']\""
    >>> a
    '"[\'BOS\']"'    # this is the representation of the string
    >>> print a
    "['BOS']"    # this is the actual content
    

    When you type an expression such as a into the console, it's the same as writing print repr(a). repr(a) returns a string that can be used to reconstruct the original value, hence the quotes around the string and the backslashes.