ascii(object)
類似于 repr()
,該函數(shù)也會返回一個用于描述 object 的字符串蝗敢。與 repr()
的不同之處在于藕夫,ascii()
在獲取 __repr__()
的返回值之后症脂,會使用轉(zhuǎn)義序列 (\x
, \u
, \U
) 來表示其中的非 ASCII 碼字符砚哗。ascii()
返回的字符串類似于 Python 2 中的 repr()
函數(shù)返回的字符串。
class Cls:
def __repr__(self):
# ascii與repr都會使用__repr__足丢,
# 但ascii會轉(zhuǎn)義其中的非ASCII字符
return "調(diào)用__repr__"
def __str__(self):
# ascii不使用__str__
return "調(diào)用__str__"
a_cls = Cls()
print("repr 的返回值:{0}".format(repr(a_cls)))
print("ascii的返回值:{0}".format(ascii(a_cls)))
輸出
repr 的返回值:調(diào)用__repr__
ascii的返回值:\u8c03\u7528__repr__
如何轉(zhuǎn)義非 ASCII 碼字符植榕?
首先再沧,補(bǔ)充一點有關(guān) Unicode 的知識:每個 Unicode 字符都有一個指定的代碼點(code point),在 Unicode 字符集中一般表示為 U+XXXX
尊残,其中 XXXX 是由 4 個或更多個16進(jìn)制數(shù)字表示的序列炒瘸。在 Python 3 中:\u
轉(zhuǎn)義序列用于插入碼點范圍在 U+0000
~ U+FFFF
之間的 Unicode 字符淤堵。\U
轉(zhuǎn)義序列用于插入碼點范圍在 U+10000
及以上的字符。
ascii()
會將非 ASCII 碼字符以 Unicode 轉(zhuǎn)義序列表示:
-
\xhh
轉(zhuǎn)義序列用于表示碼點范圍在U+007F
~U+00FF
之間的 Unicode 字符顷扩。 -
\uxxxx
轉(zhuǎn)義序列用于表示碼點范圍在U+0100
~U+FFFF
之間的 Unicode 字符拐邪。 -
\Uxxxxxxxx
轉(zhuǎn)義序列用于表示碼點范圍在U+10000
及以上的字符。
另外隘截, U+0000
~ U+007E
對應(yīng) ASCII 碼扎阶。
示例代碼:
print(ascii('μ')) # U+007F ~ U+00FF
print(ascii('鯨')) # U+0100 ~ U+FFFF
print(ascii("??")) # U+10000
輸出:
'\xb5'
'\u9cb8'
'\U0001f60a'
最后在對比一下 repr()
:
print(repr('μ'))
print(repr('鯨'))
print(repr("??"))
輸出:
'μ'
'鯨'
'??'