开发者

Having both single and double quotation in a Python string

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


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.


Use triple-quoted strings:

""" This 'string' contains "both" types of quote """
''' So ' does " this '''


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.


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


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.


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.


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


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"


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!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜