簡體   English   中英

這些代碼之間有什么區別,repr做了什么?

[英]What is the difference between these codes, and what does the repr do?

1。

>>> s = u"4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf"
>>> print s
4-12個英文字母、數字和下划線
>>> print repr(s)
u'4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf'

2。

print repr("4-12個英文字母、數字和下划線")
'4-12\xb8\xf6\xd3\xa2\xce\xc4\xd7\xd6\xc4\xb8\xa1\xa2\xca\xfd\xd7\xd6\xba\xcd\xcf\xc2\xbb\xae\xcf\xdf'

1和2是不同的,但原來的字符串是相同的,都是'4-12個英文字母,數字和下划線'

repr到底做了什么?

相同的值是:

>>> print '4-12個英文字母、數字和下划線'.decode('gb2312').encode('unicode-escape')
4-12\u4e2a\u82f1\u6587\u5b57\u6bcd\u3001\u6570\u5b57\u548c\u4e0b\u5212\u7ebf

我將對此進行一次嘗試,'repr'是對象的機器表示,而'print'顯示對象的人類可讀表示。 內置方法' repr ',' str '和' unicode '可供程序員用來實現對象的不同可打印表示。 這是一個簡單的例子

class PrintObject(object):
    def __repr__(self):
        return 'repr'

    def __str__(self):
        return 'str'

    def __unicode__(self):
        return 'unicode'

現在,如果您將此對象加載到python shell中並使用它,您可以看到這些不同的方法如何用於表示對象的可打印表示

Python 2.6.4 (r264:75821M, Oct 27 2009, 19:48:32)
[GCC 4.0.1 (Apple Inc. build 5493)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> from printobject import PrintObject
>>> printObj = PrintObject()
>>> printObj
>>> repr(printObj)
'repr'
>>> str(printObj)
'str'
>>> unicode(printObj)
u'unicode'

如果只鍵入實例並返回,則使用' repr '方法

>>> printObj
repr

如果在實例上使用print,則使用' str '方法

>>> print(printObj)
str

如果在unicode字符串中使用實例,則使用' unicode '方法。

>>> print(u'%s' % printObj)
unicode

當你開始編寫自己的類時,這些方法非常方便。

關於repr

>>> help(repr)
Help on built-in function repr in module __builtin__:

repr(...)
    repr(object) -> string

    Return the canonical string representation of the object.
    For most object types, eval(repr(object)) == object.

在第一種情況下,Python解釋器通過終端編碼自動解碼傳遞給它的字節,因為它是unicode文字。 打印它的repr()會產生Unicode轉義序列。

在第二種情況下,不進行解碼,因為它是str literal,因此它的repr()由對應於終端編碼中的字符的字節轉義序列組成(在這種情況下,GB2312)。

在第一種情況下,您將獲得unicode對象的repr。 這在概念上是一系列unicode字符,repr為您提供這些字符的unicode代碼點序列作為轉義序列。 即'\\ u4e2a'是代碼點20010(0x4e2a是十六進制表示),顯示為“個”。

在第二種情況下,您將獲得字符串對象的repr。 字符串本質上是8位值的序列,沒有關於這些值如何與字符相關的內部知識。 在提示符下打印或輸入這些字符時,將使用系統的默認編碼對其進行解釋。 當您打印對象的repr時,您會看到構成它的原始字節 - 可打印的ASCII字符按原樣打印,其他所有內容都顯示為轉義序列(即\\ xb8是值184(以十六進制寫入0xB8) )。 在系統的編碼(gb2312)中,字節序列[184,246]('\\ xb8 \\ xf6')對應於unicode代碼點0x4e2a。 然而,字符串不知道它是什么編碼,或者甚至它代表一系列字符,所以它的repr只給你原始的底層數據。 要將其轉換為unicode對象,您需要從此數據中解碼它,指示應如何解釋原始數據:

>>> s=s.decode('gb2312')

在python3中,“字符”和“數據”之間的區別變得更加清晰,因為str對象被重命名為“bytes”,而現在的unicode字符串變成了字符串。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM