gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:59 26 4
gpt4 key购买 nike

我正在参加初学者 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

关于python - 输出打印转义字符 [\],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41817647/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com