作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
#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/
我是一名优秀的程序员,十分优秀!