29

I'm trying to have a string that contains both single and double quotation in Python (' and "). However, Python always automatically corrects this to (\', "). I wonder if there's a way to put a double quotation and a single quotation together as it is.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
GHO
  • 321
  • 1
  • 3
  • 4
  • Do you mean the backslash is there when you print it, or only when you look at it in the interpreter? – Tom Zych Sep 20 '11 at 14:47
  • 9
    "python always automatically corrects"? Where? How? Please `print` the output to be **sure** what you're getting. Note that what you see from `repr()` and what you see at `>>>` prompt don't match what is **actually** in the string. The `repr()` and `>>>` versions are Python source code. Not the actual value. Please **update** your question with specific examples. – S.Lott Sep 20 '11 at 14:48

9 Answers9

48

Use triple quotes.

"""Trip'le qu"oted"""

or

'''Ag'ain qu"oted'''

Keep in mind that just because Python reprs a string with backslashes, doesn't mean it's actually added any slashes to the string, it may just be showing special characters escaped.

Using an example from the Python tutorial:

>>> len('"Isn\'t," she said.')
18
>>> len('''"Isn't," she said.''')
18

Even though the second string appears one character shorter because it doesn't have a backslash in it, it's actually the same length -- the backslash is just to escape the single quote in the single quoted string.

Another example:

>>> for c in '''"Isn't," she said.''':
...     sys.stdout.write(c)
... 
"Isn't," she said.
>>> 

If you don't let Python format the string, you can see the string hasn't been changed, it was just Python trying to display it unambiguously.

See the tutorial section on strings.

agf
  • 171,228
  • 44
  • 289
  • 238
  • Thanks for the response. However, when I typed s = """ ' " """, and when I check the value of s, it still displays ' \' " '. I'm passing this string to the command line, so it has to be ' ' " '. – GHO Sep 20 '11 at 14:57
  • @GHO see S.Lott's comment above. – Daniel Roseman Sep 20 '11 at 14:59
  • @GHO I think I explained that pretty well in the answer (I added another example) -- the `\ ` isn't actually there (in the string), Python is just using it to show that the `'` doesn't end the string, as opposed to the ones at the beginning and end. It doesn't actually change your string, just how it is displayed. – agf Sep 20 '11 at 15:06
  • 1
    One gotcha this doesn't cover: if your string ends with the same kind of quote you're tripling, so that you have four in a row, Python will grab the first three and give you an "EOL while scanning string literal" for the fourth. Workarounds are to use the opposite triple quote `"'''`, end with a space `" """`, or escape the ending quote `\""""`. – Noumenon Mar 03 '19 at 14:31
6

Use triple-quoted strings:

""" This 'string' contains "both" types of quote """
''' So ' does " this '''
multipleinterfaces
  • 8,913
  • 4
  • 30
  • 34
  • Thanks for your response. However, I still have the problem as I commented above. Btw, I'm using python 2.7 – GHO Sep 20 '11 at 14:58
  • 2
    @GHO: "still have the problem". That means (1) post the actual code in the question. (2) post the actual output from an actual `print` statement. In the question. (3) post the actual error you're actually getting. In the question. We -- sadly -- can't guess what code you're using. – S.Lott Sep 20 '11 at 15:31
5

To add both the single and double quote on python use screened (escaped) quotes. Try this for example:

print(" just display ' and \" ")

The \" tells python this is not the end of the quoted string.

phd
  • 82,685
  • 13
  • 120
  • 165
4

The actual problem is , the print() statement doesn't print the \ but when you refer to the value of the string in the interpreter, it displays a "\" whenever an apostrophe is used . For instance, refer the following code:

    >>> s = "She said, \"Give me Susan's hat\""
    >>> print(s)
    She said, "Give me Susan's hat"
    >>> s
    'She said, "Give me Susan\'s hat"'

This is irrespective of whether you use single, double or triple quotes to enclose the string.

    >>> s = """She said, "Give me Susan's hat" """
    >>> s
    'She said, "Give me Susan\'s hat" '

Another way to include this :

    >>> s = '''She said, "Give me Susan's hat" '''
    >>> s
    'She said, "Give me Susan\'s hat" '
    >>> s =  '''She said, "Give me Susan\'s hat" '''
    >>> s
    'She said, "Give me Susan\'s hat" '

So basically, python doesn't remove the \ when you refer to the value of s but removes it when you try to print. Despite this fact, when you refer to the length of s, it doesn't count the "\". For eg.,

    >>> s = '''"''"'''
    >>> s
    '"\'\'"'
    >>> print(s)
    "''"
    >>> len(s)
    4
  • 1
    there is nothing that can be done about this?. because am trying to pass the string to subprocess as a bash command and that extra back slash keeps messing up the execution. – Oxax Jun 10 '20 at 16:25
3

This also confused me for more than a day, but I've digested it now.

First, let's understand that the string will output DOUBLE quotes if it passes DOUBLE the tests:

  1. Contains a single quote
  2. Contains NO double quotes

That's the easiest manner to remember it.

The literal "doesn't" passes the first test because of the apostrophe, which counts as a single quote. Then, we re-examine it and find it does not contain any double quotes inside of the enclosure. Therefore, the string literal outputs as a double quote:

>>> "doesn't"
"doesn't"

There is no need to escape a single quote with a backslash in the output because the enclosure is composed of double quotes!

Now consider the literal '"Isn\'t," they said.' This literal passes the first test because it contains an apostrophe, even if it's escaped. However, it also contains double quotes, so it fails the second test. Therefore, it outputs as a single quote:

>>> '"Isn\'t," they said.'
'"Isn\'t," they said.'

And because the enclosure is composed of single quotes, the escape is needed in the output.

If it weren't for the backslash in the output, the EOL (end of line) would have been reached while scanning the literal.

Finally, consider "\"Isn't,\" they said."

There is a single quote inside of the literal, so it does pass the first test...but fails the second. The output should enclose the string literal in single quotes:

>>> "\"Isn't,\" they said."
'"Isn\'t," they said.'

Therefore, the escape is needed to prevent a premature EOL.

0

Although its more verbose, an alternative way would be to do the following:

str1 = 'the part that has double "s" in it'

str1 = str1 + " the part that has single 's' in it"
Ruli
  • 2,592
  • 12
  • 30
  • 40
kris
  • 1
0

You can either (1) enclose the string in double quotes and escape the double quotes with a \ or (2) enclose the string in single quotes and escape the single quotes with a \. For example:

>>> print('She is 5\' 6" tall.')
She is 5' 6" tall.
>>> print("He is 5' 11\" tall.")
He is 5' 11" tall.
JPaget
  • 969
  • 10
  • 13
0

In f-string, I can't use back slash. At that time, Using chr() may be solution!

print(f"- tokenizer: {' '.join(str(type(tokenizer)).split(chr(39))[1:-1])}")

Unicode HOWTO

Jihee Ryu
  • 1
  • 2
0

In certain cases, using triple quotes seems to not work for me.

For instance, I once confronted with the problem to manipulate this script to be more dynamic.

listed = drive.ListFile({'q': "title contains '.mat' and '1GN8xQDTW4wC-dDrXRG00w7CymjI' in parents"}).GetList()

In the part after 'q':, there is a string with double and single quotes. So, I intend to independently change the file type ('.mat) and the folder ID ('1GN...').

Dealing with the issue, I use .format to manipulate the script above and turn it into this one

listed = drive.ListFile({'q': "title contains '{}' and '{}' in parents".format(file_type, folder_id)}).GetList()

May it helps to give certain clue if using triple quotes is not possible for you.

cheers!

Syifa
  • 1