repr()与str的区别

str  事实上和 int, long一样,是一种类型  str可以让字符串更易于阅读

repr() 仅是一个函数,把字符串转换为合法的Python的表达式

示例如下:

 1 >>> type('hello')
 2 <class 'str'>
 3 >>> a = 'hello'
 4 >>> type(a)
 5 <class 'str'>
 6 >>> type(repr(a))
 7 <class 'str'>
 8 >>> print(repr(a))
 9 'hello'
10 >>> print(a)
11 hello
 1 >>> a = 'hello'
 2 >>> print( a + ' world!' )
 3 hello world!
 4 >>> print(repr(a) + 'world!')
 5 'hello'world!

 区别

str()函数的目标是一般用户的可读性,返回一个更适合人阅读的 string。

而repr()则返回一个更适合python解析器阅读的strng,同时会返回Python解析器能够识别的数据细节,但这些细节对一般用户来说是多余的。而且repr()转换后的String对象可以通过求值运算eval()来还原到转换之前的对象,相比之下str()通常不需要eval()去处理。

原文地址:https://www.cnblogs.com/Sky-Aces/p/8325459.html