Having both single and double quotation in a python string

后端 未结 6 619
悲&欢浪女
悲&欢浪女 2020-11-29 09:19

Hi I\'m trying to have a string that contains both single and double quotation in python -- (\'\"). The reason I need this expression is to use as an input to some external

6条回答
  •  甜味超标
    2020-11-29 09:43

    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
    

提交回复
热议问题