Search code examples
pythonraw-input

output prints an escape character [ \ ]


I'm taking a beginner Python course and this was one of the activity lessons:

my code:

print "How old are you?",
age = raw_input()
print "How tall are you?",
height = raw_input()
print "How much do you weigh?"
weight = raw_input()
print "So, you're %r old, %r tall and %r heavy." % (age, height, weight)

I then run it through Powershell and input the data when prompted, but when I type in 5'9" for height and it prints out the input in final string it looks like this:

So, you're '24' old, '5\'9"' tall and '140 lbs' heavy. 

How do I get the backslash to go away?


Solution

  • By using the %r format flag, you're printing the repr of the string. The distinction is explained well in this question, but in your case specifically:

    >>> s = '5\'9"' # need to escape single quote, so it doesn't end the string
    >>> print(s)
    5'9"
    >>> print(str(s))
    5'9"
    >>> print(repr(s))
    '5\'9"'
    

    The repr, in seeking to be unambiguous, has surrounded the string in single-quotes and escaped each of the single quotes inside the string. This is nicely parallel with how you type out the constant string in source code.

    To get the result you're looking for, use the %s format flag, instead of %r, in your format string.