补丁——str()与repr()

str(): 函数返回一个用户易读的表达形式。python

repr(): 产生一个解释器易读的表达形式。函数

必定要搞懂这两句话,重点就在于str是给人类看的,而repr是给python解释器看的。spa

示例代码:code

#python3中没有多大区别字符串

>>> print('你好')
你好
>>> str('hello')
'hello'
>>> repr('hello')
"'hello'"
>>> str('你好')
'你好'
>>> repr('你好')
"'你好'"
>>>co

#python2中区别很大字符

>>> str('hello')
    'hello'
    >>> repr('hello')
    "'hello'"

    >>> str('你好')
    '\xc4\xe3\xba\xc3'
    >>> repr('你好')
    "'\\xc4\\xe3\\xba\\xc3'"
background

这几行代码说明了一个现象python在面对用户和解释器时准备了两种方案,人看得懂的和机器看的懂得。str和repr输出的都是字符串,repr输出的是标准的字符串,机器阅读更方便;str输出的是人所能阅读的字符串,本质也是repr输出的字符串。阅读

print后的str()和repr()

来看代码:

>>> print str('你好') 你好 >>> print repr('你好') '\xc4\xe3\xba\xc3'
相关文章
相关标签/搜索