TorakRoi TorakRoi - 1 year ago 86
Python Question

Python adding \ when printing '

In the interpreter, when I'm writing the code

"it's 42\""

To make python display

'it's 42"'

It's displaying

'it\'s 42"'

Instead. Now, I would like to understand why, more then getting around that.

Answer Source

When you type to the shell:

"it's 42\""

It displays the string variable created from what your wrote, and python defaults to ' usage. So you get:

'it\'s 42"'

which, when you think about it, is the exact same string you wrote! You used "" to denote the string and escaped the extra ", but python uses in the shell ' and escapes the extra one in the it ' s.

To show the string properly use the print method which reads the escapes properly. I guarantee printing your version or the version your shell returns will both yield what you wanted.

On a side note you can use triple quotes to skip escapes all together:

'''it's 42"'''

The caveat is you can't use triple double quotes, because python will think the end of your string is part of the string enclosure.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download