输出打印转义字符[\]

2024-04-25 07:24:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在上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“作为height时,它会以final string的形式输出输入,如下所示:

^{pr2}$

我如何让反斜杠消失?在


Tags: 代码youinputagerawoldare课程
2条回答

通过使用%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。在

不要在格式中使用repr %r,使用%s,字符串只是简单地插值而不转义任何字符:

print "So, you're %s old, %s tall and %s heavy." % (age, height, weight)
#                  ^       ^           ^

相关问题 更多 >