簡體   English   中英

通過強制轉換為str可逆地轉換Python unicode嗎?

[英]Is converting Python unicode by casting to str reversible?

在Python u.encode(someencoding) unicode字符串u轉換為(字節)字符串的正確方法是調用u.encode(someencoding)

不幸的是,我以前並不知道,我使用過str(u)進行轉換。 特別是,我調用str(u)u強制為字符串,以便可以使其成為有效的擱置鍵(必須為str)。

由於我沒有遇到任何UnicodeEncodeError ,所以我想知道此過程是否可逆/無損。 也就是說,我是否可以通過u = str(converted_unicode) (或Python 3中的u = bytes(converted_unicode) )來獲取原始u

在Python 2中,如果使用str()的轉換成功,則可以反轉結果。 unicode值上使用str()等同於使用unicode_value.encode('ascii') ,相反就是簡單地使用str_value.decode('ascii') 使用unicode(str_value)將使用相同的隱式ASCII編解碼器進行解碼。

在Python 3中,對unicode值調用str()只會給您返回相同的對象,因為在Python 3中str() Unicode類型。 在沒有編碼的情況下對Unicode值使用bytes()失敗,您始終必須在Python 3中使用顯式編解碼器在strbytes之間進行轉換。

暫無
暫無

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

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