python中repr_了解Python中的repr()函数

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:

Why do I get the double quotes when I do repr(x)? (I don't get them

when I do str(x))

Why do I get 'foo' when I do eval("'foo'") and not x which is the

object?

解决方案>>> 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 "", line 1, in

eval('foo')

File "", line 1, in

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'.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值