Search code examples
pythonpython-3.xstringquoting

Printing Single Quote inside the string


I want to output

XYZ's "ABC"

I tried the following 3 statements in Python IDLE.

  • 1st and 2nd statement output a \ before '.
  • 3rd statement with print function doesn't output \ before '.

Being new to Python, I wanted to understand why \ is output before ' in the 1st and 2nd statements.

>>> "XYZ\'s \"ABC\""
'XYZ\'s "ABC"'

>>> "XYZ's \"ABC\""
'XYZ\'s "ABC"'

>>> print("XYZ\'s \"ABC\"")
XYZ's "ABC"

Solution

  • Here are my observations when you call repr() on a string: (It's the same in IDLE, REPL, etc)

    • If you print a string(a normal string without single or double quote) with repr() it adds a single quote around it. (note: when you hit enter on REPL the repr() gets called not __str__ which is called by print function.)

    • If the word has either ' or " : First, there is no backslash in the output. The output is gonna be surrounded by " if the word has ' and ' if the word has ".

    • If the word has both ' and ": The output is gonna be surrounded by single quote. The ' is gonna get escaped with backslash but the " is not escaped.

    Examples:

    def print_it(s):
        print(repr(s))
        print("-----------------------------------")
    
    print_it('Soroush')
    print_it("Soroush")
    
    print_it('Soroush"s book')
    print_it("Soroush's book")
    
    print_it('Soroush"s book and Soroush\' pen')
    print_it("Soroush's book and Soroush\" pen")
    

    output:

    'Soroush'
    -----------------------------------
    'Soroush'
    -----------------------------------
    'Soroush"s book'
    -----------------------------------
    "Soroush's book"
    -----------------------------------
    'Soroush"s book and Soroush\' pen'
    -----------------------------------
    'Soroush\'s book and Soroush" pen'
    -----------------------------------
    

    So with that being said, the only way to get your desired output is by calling str() on a string.

    • I know Soroush"s book is grammatically incorrect in English. I just want to put it inside an expression.