您的位置:首页 > 编程语言 > Python开发

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

2017-03-19 16:51 501 查看

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 as
b'string'
or using a
bytes
constructor.

参考:

http://stackoverflow.com/questions/2220699/whats-the-difference-between-eval-exec-and-compile-in-python 详细讲解了eval和exec的区别

http://www.mojidong.com/python/2013/05/10/python-exec-eval/

https://segmentfault.com/a/1190000004450876 bytes()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: