Skip to main content
 首页 » 编程设计

python之输出打印转义字符 [\]

2025年05月04日14grandyang

我正在参加初学者 Python 类(class),这是事件类(class)之一:

我的代码:

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.  

如何让反斜杠消失?

请您参考如下方法:

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