簡體   English   中英

Python打印無法同時打印Unicode和字符串

[英]Python print failing to print Unicode and string same time

以下是我觀察到的幾種情況。 想知道為什么Python的打印效果如此,以及可能的修復方法。

>>> print "%s" % u"abc" # works
>>> print "%s" % "\xd1\x81" # works
>>> print "%s %s" % (u"abc", "\xd1\x81") # Error

對於以上(最后),我得到: UnicodeDecodeError: 'ascii' codec can't decode byte 0xd1 in position 0: ordinal not in range(128)

但是,這有效

>>> print "%s %s" % ("abc", "\xd17\x81") # works

當我這樣做

>>> print "%s %s" % (u"abc", u"\u0441") # Error

其引發的UnicodeEncodeError: 'charmap' codec can't encode character u'\с' in position 4: character maps to <undefined>

在Python 2中混合Unicode字符串和字節字符串時,使用默認的ascii編解碼器將字節字符串隱式強制為Unicode。 如果失敗,您將收到UnicodeDecodeError

當您打印Unicode字符串時,它們將以當前輸出編碼隱式編碼。 如果失敗,您將收到UnicodeEncodeError

所以:

>>> print "%s" % u"abc"

是真的:

>>> print unicode("%s",'ascii') % u"abc" # and valid

但是以下內容僅在您表示“不會引發錯誤”時有效。 如果希望它打印U + 0441字符,則僅在輸出編碼為UTF-8時才這樣做。 它在Windows系統上打印垃圾。

>>> print "%s" % "\xd1\x81"

由於隱式Unicode解碼,以下給出錯誤:

print "%s %s" % (u"abc", "\xd1\x81")

這實際上是:

print unicode("%s %s",'ascii') % (u"abc", unicode("\xd1\x81",'ascii'))

\\xd10x81不在ASCII范圍0-7Fh中。

最后一個錯誤意味着您的輸出編碼不是UTF-8,因為它無法將編碼為輸出編碼支持的字符以進行打印。 UTF-8可以編碼所有Unicode字符。

這是對的。 輸出時,必須將unicode對象編碼為所需的字符編碼,即utf-8或其他。 unicode (包括所有u“”文字)視為一種抽象,必須在序列化之前將其編碼為utf-8類的東西。

您可以使用s.encode('utf-8')unicode對象s編碼為utf-8 Python 2中的str對象是字節編碼的,因此您不會因為“ \\ xd17 \\ 81”之類的錯誤而出錯,因為它們已經被編碼了。

我建議您使用Python 3而不是Python 2,因為這更加直觀。

暫無
暫無

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

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