1

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?

Harshdeep Sokhey
  • 324
  • 5
  • 15

2 Answers2

4

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.

Community
  • 1
  • 1
Haldean Brown
  • 12,411
  • 5
  • 43
  • 58
  • Thank you for explaining this to me! I'm still trying to get the hang of understanding the differences between the different input formats. Tyty! – Rebecca Noel Jan 23 '17 at 23:50
  • 3
    No worries! If this or Moses's answer answered your question, don't forget to accept one of them using the checkmark on the left; that'll take your question out of the queue of questions that need answers. Welcome to StackOverflow! – Haldean Brown Jan 23 '17 at 23:59
2

Don't use repr %r in your formatting, use %s and the strings are simply interpolated without escaping any character:

print "So, you're %s old, %s tall and %s heavy." % (age, height, weight)
#                  ^       ^           ^
Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139