pythonstringescaping

How to accept strings containing escape characters python


If the user inputs a string containing an escape character (e.g. "Example\" or "C:\Users...), I want to accept it exactly as is. In other words, I'm trying to circumvent the Syntax error thrown when input like the above is processed.

I feel like it should be simple, but the answer eludes me. Any help?

EDIT: I'm on python 3


Solution

  • Don't use input(); use raw_input() instead when accepting string input.

    input() (on Python 2) tries to interpret the input string as Python, raw_input() does not try to interpret the text at all, including not trying to interpret \ backslashes as escape sequences:

    >>> raw_input('Please show me how this works: ')
    Please show me how this works: This is \n how it works!
    'This is \\n how it works!'
    

    On Python 3, use just input() (which is Python 2's raw_input() renamed); unless you also use eval() it will not interpret escape codes:

    >>> input('Please show me how this works: ')
    Please show me how this works: This is \n how it works!
    'This is \\n how it works!'