我参加了一门初学Python课程,这是其中一项活动课程:
我的代码:
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)
然后我通过Powershell运行它并在提示时输入数据,但是当我输入5' 9"对于高度,它打印出最终字符串中的输入,如下所示:
So, you're '24' old, '5\'9"' tall and '140 lbs' heavy.
如何让反斜杠消失?
答案 0 :(得分:4)
通过使用%r
格式标志,您将打印字符串的repr。这种区别在this question中得到了很好的解释,但在具体情况下如下:
>>> 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"'
repr在寻求明确时,用单引号包围了字符串并转义了字符串中的每个单引号。这与你在源代码中输入常量字符串的方式非常平行。
要获得您要查找的结果,请在格式字符串中使用%s
格式标记,而不是%r
。
答案 1 :(得分:2)
请勿在格式化中使用repr %r
,使用%s
并简单地插入字符串而不转义任何字符:
print "So, you're %s old, %s tall and %s heavy." % (age, height, weight)
# ^ ^ ^