问题:了解Python中的repr()函数

repr():对象的可评估字符串表示形式(可以“ eval()”表示它,这是一个评估为Python对象的字符串表示形式)

换一种说法:

>>> x = 'foo'
>>> repr(x)
"'foo'"

问题:

  1. 为什么我得到双引号repr(x)?(这样做的时候我不懂str(x)
  2. 为什么我会'foo'当我做eval("'foo'"),而不是X也就是对象?

repr(): evaluatable string representation of an object (can “eval()” it, meaning it is a string representation that evaluates to a Python object)

In other words:

>>> x = 'foo'
>>> repr(x)
"'foo'"

Questions:

  1. Why do I get the double quotes when I do repr(x)? (I don’t get them when I do str(x))
  2. Why do I get 'foo' when I do eval("'foo'") and not x which is the object?

回答 0

>>> x = 'foo'
>>> x
'foo'

因此,名称x将附加到'foo'字符串。例如repr(x),当您调用时,解释器放'foo'而不是,x然后调用repr('foo')

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr实际调用一个魔术方法__repr__x,这给包含该值的表示'foo'分配给x。因此它会'foo'在字符串内返回""结果"'foo'"。的想法repr是给出一个包含一系列符号的字符串,我们可以在解释器中键入该符号,并获得与作为参数发送给的相同值repr

>>> eval("'foo'")
'foo'

调用时eval("'foo'"),与'foo'在解释器中键入的相同。就像我们""在解释器中直接键入外部字符串的内容一样。

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

如果调用eval('foo'),则与foo在解释器中键入的相同。但是没有foo可用的变量,并且引发了异常。

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str只是对象的字符串表示形式(请记住,x变量是指'foo'),因此此函数返回字符串。

>>> str(5)
'5'

整数的字符串表示形式5'5'

>>> str('foo')
'foo'

并且字符串的字符串表示形式'foo'是相同的字符串'foo'

>>> x = 'foo'
>>> x
'foo'

So the name x is attached to 'foo' string. When you call for example repr(x) the interpreter puts 'foo' instead of x and then calls repr('foo').

>>> repr(x)
"'foo'"
>>> x.__repr__()
"'foo'"

repr actually calls a magic method __repr__ of x, which gives the string containing the representation of the value 'foo' assigned to x. So it returns 'foo' inside the string "" resulting in "'foo'". The idea of repr is to give a string which contains a series of symbols which we can type in the interpreter and get the same value which was sent as an argument to repr.

>>> eval("'foo'")
'foo'

When we call eval("'foo'"), it’s the same as we type 'foo' in the interpreter. It’s as we directly type the contents of the outer string "" in the interpreter.

>>> eval('foo')

Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    eval('foo')
  File "<string>", line 1, in <module>
NameError: name 'foo' is not defined

If we call eval('foo'), it’s the same as we type foo in the interpreter. But there is no foo variable available and an exception is raised.

>>> str(x)
'foo'
>>> x.__str__()
'foo'
>>> 

str is just the string representation of the object (remember, x variable refers to 'foo'), so this function returns string.

>>> str(5)
'5'

String representation of integer 5 is '5'.

>>> str('foo')
'foo'

And string representation of string 'foo' is the same string 'foo'.


回答 1

您在交互式解释器上获得的反馈也将使用repr。当您键入表达式(顺便说一句expr)时,解释器基本上会执行result = expr; if result is not None: print repr(result)。因此,在您的例子中,第二行格式化字符串foo为表示你要('foo')。然后解释创建repr的esentation ,让你用双引号。

为什么当我将%r与双引号和单引号转义结合使用并打印出来时,它以我将其写入.py文件的方式而不是我希望看到的方式打印出来?

我不确定您在这里问什么。文本single ' and double " quotes在运行时repr,包含一种引号的转义符。当然可以,否则Python规则将不是有效的字符串文字。这正是您要求通过调用repr

还要注意,eval(repr(x)) == x类推并非字面意思。这是一个近似值,适用于大多数(所有?)内置类型,但主要的是,通过查看repr输出,您可以很好地了解类型和逻辑“值” 。

The feedback you get on the interactive interpreter uses repr too. When you type in an expression (let it be expr), the interpreter basically does result = expr; if result is not None: print repr(result). So the second line in your example is formatting the string foo into the representation you want ('foo'). And then the interpreter creates the representation of that, leaving you with double quotes.

Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I’d write it in my .py file but not the way I’d like to see it?

I’m not sure what you’re asking here. The text single ' and double " quotes, when run through repr, includes escapes for one kind of quote. Of course it does, otherwise it wouldn’t be a valid string literal by Python rules. That’s precisely what you asked for by calling repr.

Also note that the eval(repr(x)) == x analogy isn’t meant literal. It’s an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical “value” from looking the the repr output.


回答 2

str()用于为最终用户创建输出,而repr()用于调试开发,它代表对象的正式名称。

例:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'

从输出中我们看到repr()显示了date对象的正式表示形式。

str() is used for creating output for end user while repr() is used for debuggin development.And it’s represent the official of object.

Example:

>>> import datetime
>>> today = datetime.datetime.now()
>>> str(today)
'2018-04-08 18:00:15.178404'
>>> repr(today)
'datetime.datetime(2018, 4, 8, 18, 3, 21, 167886)'

From output we see that repr() shows the official representation of date object.


回答 3

1)的结果repr('foo')字符串 'foo'。在您的Python Shell中,表达式的结果也被表示为表示形式,因此您基本上可以看到repr(repr('foo'))

2)eval计算表达式的结果。结果始终是一个(例如数字,字符串或对象)。多个变量可以引用相同的值,如下所示:

x = 'foo'
y = x

x和y现在引用相同的值。

3)我不知道你在这里是什么意思。您可以发表一个例子,以及您想看到的内容吗?

1) The result of repr('foo') is the string 'foo'. In your Python shell, the result of the expression is expressed as a representation too, so you’re essentially seeing repr(repr('foo')).

2) eval calculates the result of an expression. The result is always a value (such as a number, a string, or an object). Multiple variables can refer to the same value, as in:

x = 'foo'
y = x

x and y now refer to the same value.

3) I have no idea what you meant here. Can you post an example, and what you’d like to see?


回答 4

当你说

foo = 'bar'
baz(foo)

您没有传递foo给该baz函数。 foo在这种情况下'bar',只是一个用于表示值的名称,该值将传递给baz函数。

When you say

foo = 'bar'
baz(foo)

you are not passing foo to the baz function. foo is just a name used to represent a value, in this case 'bar', and that value is passed to the baz function.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。