gpt4 book ai didi

python - 艰难地学习 Python,练习 10.4

转载 作者:行者123 更新时间:2023-11-28 22:04:02 24 4
gpt4 key购买 nike

#Combine %r with double-quote and single-quote escapes and print them out. 
#Compare %r with %s. Notice how %r prints it the way you'd write it in your file,
#but %s prints it the way you'd like to see it?

这是我为练习写的:

1) mybugs1 = "Guido said: %r and moved on." %'I \'love\' \"my\" bugs'

2) mybugs2 = "Stallman said: %s and moved on." % 'I \'love\' \"my\" bugs'

3) print mybugs1

4) print mybugs2

输出

Guido said: 'I \'love\' "my" bugs' and moved on.

Stallman said: I 'love' "my" bugs and moved on.

问题

%r 并没有像我在 .py 文件中那样打印所有内容(例如,它在第 1 行打印“my”而不是\“my\”)。为什么?

最佳答案

在 python 中有几种写字符串文字的方法,单引号或双引号,单行或多行,原始或正常。但是,这些都没有保留在字符串本身中;一旦解析器解析了它,就不会留下任何关于如何它在源代码中呈现的信息;它甚至不需要在源代码中,您可以动态生成字符串,例如,通过从文件中读取它、询问用户或将数字转换为字符串。

因此,当您repr() 一个字符串时,python 猜测 哪种方式将其格式化为看起来像文字。它使用的规则很简单,如果字符串包含单引号但没有双引号,它使用单行、双引号、非原始文字;在所有其他情况下,它使用单行、单引号、非原始文字;换句话说,python 更喜欢单引号,但是如果它正在格式化一个有单引号但没有双引号的字符串,它可以 repr() 没有反斜杠的字符串通过使用双引号字符串转义引号.

请记住,repr() 不会返回您键入的内容,因为它不知道您键入的内容;您可能永远不会全部输入。它返回一些可以解析回相同值的东西。身份* 是:

x == eval(repr(x))

不是

x == repr(eval(x))

* repr() 对此也不是神奇的,并非所有对象都以保留此约束的方式实现 __repr__。 repr 主要用于提供有用的调试信息,而不是用于生成 python 代码

关于python - 艰难地学习 Python,练习 10.4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7791150/

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