python知识点: repr()/str()/eval()/exec()/bytes()

eval vs exec:

Basically, eval is used to evaluate a single dynamically generated Python expression, and exec is used to execute dynamically generated Python code only for its side effects.

eval and exec have these two differences:

1.eval accepts** only a single expression**, exec can take** a code block that has Python statements: loops, try: except:, class and function/method definitions and so on**.

An expression in Python is whatever you can have as the value in a variable assignment:
a_variable = (anything that you can put into these parentheses is an expression)
2. eval returns the value of the given expression, whereas exec ignores the return value from its code, and always returns None (in Python 2 it is a statement and cannot be used as an expression, so it really does not return anything).
Additionally in Python versions 1-2, exec was a statement, because CPython needed to produce a different kind of code object for functions that used exec for its side effects inside the function; exec is now a function in Python 3.

eval(expression[, globals[, locals]])

>>> exec('print "Hi"')
Hi
>>> eval('print "Hi"')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    print "Hi"
        ^
SyntaxError: invalid syntax
>>> eval('a = 2')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1
    a = 2
      ^
SyntaxError: invalid syntax
>>> exec('a = 2')
>>> a
2
>>> l = [1,23,4]
>>> repr(l)
'[1, 23, 4]'
>>> eval(repr(l))
[1, 23, 4]
>>> eval("{'A':1,'B':2}")
{'A': 1, 'B': 2}

repr vs str:

str(),repr()返回的是一个对象的字符串表示,也就是说绝大多数情况下可以通过求值运算(使用内建函数eval())重新得到该对象。
但str()则有所不同,str()致力于生成一个对象的可读性好的字符串表示,它的返回结果通常无法用于eval()求值,但很适合用于print语句输出。
而且,并不是所有repr()返回的字符串都能够用 eval()内建函数得到原来的对象。 也就是说 repr() 输出对 Python比较友好,而str()的输出对用户比较友好;

>>> s = 123
>>> str(s)
'123'
>>> repr(s)
'123'
>>> s = 'Hi'
>>> str(s)
'Hi'
>>> repr(s)
"'Hi'"

bytes()

Bytes 对象只负责以二进制字节序列的形式记录所需记录的对象,至于该对象到底表示什么(比如到底是什么字符)则由相应的编码格式解码所决定。我们可以通过调用 bytes() 类(没错,它是类,不是函数)生成 bytes 实例,其值形式为 b’xxxxx’,其中 ‘xxxxx’ 为一至多个转义的十六进制字符串(单个 x 的形式为:\xHH,其中 \x 为小写的十六进制转义字符,HH 为二位十六进制数)组成的序列,每个十六进制数代表一个字节(八位二进制数,取值范围 0-255),对于同一个字符串如果采用不同的编码方式生成 bytes 对象,就会形成不同的值:
Python 3 adopted Unicode as the language’s fundamental string type and denoted 8-bit literals either asb'string' or using abytes constructor.

参考:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值