簡體   English   中英

Python2&3:比較str和unicode

[英]Python2&3 : compare str and unicode

我在一個項目中苦苦掙扎,試圖使相同的代碼在Python2.6,Python 2.7和Python 3.x中運行。

該項目使用python_2_unicode_compatible類裝飾器 ,以便以str類型存儲非Unicode值。

我必須測試一個函數foo返回一個str類型(不是一個unicode類型); 返回的值填充有非ASCII字符。

我想要做的就是針對我自己的字符串測試此函數返回的值,例如:

from __future__ import unicode_literals  # so that "àbcéfg" will be read u"àbcéfg"
bool_test = (foo() == "àbcéfg")

我很困惑,因為“àbcéfg”在Python2中將被視為unicode字符串,而在Python3中將被視為str字符串。

例如,對於Python2,此代碼引發以下錯誤:

Unicode相等比較無法將兩個參數都轉換為Unicode-將它們解釋為不相等

有沒有實現Python2和Python3通用的比較的獨特方法?

我嘗試了幾種解決方案(例如,將str轉換為字節),但均未成功。

有什么辦法可以幫助我嗎?

您正在正確比較事物,但是foo()不會返回Unicode值。 它在Python 2中返回字節字符串:

>>> def foo():
...     return u"àbcéfg".encode('utf8')
... 
>>> foo() == u"àbcéfg"
__main__:1: UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal
False

修復foo()或將其傳遞給將解碼返回值(如果不是Unicode值)的函數(此處使用six模塊橋接Python 2和3中的二進制類型):

import six

def ensure_unicode(value, encoding='utf8'):
    if isinstance(value, six.binary_type):
        return value.decode(encoding)
    return value

bool_test = ensure_unicode(foo()) == "àbcéfg"

如果foo()打算在Python 2中返回一個字節字符串,而在Python 3中返回一個Unicode字符串,則以上內容將繼續起作用,但在Python 2中不會專門驗證它是否正確; 您可以為此添加一個單獨的isinstance()測試:

foo_result = foo()
bool_test = isinstance(foo_result, str) and ensure_unicode(foo_result) == "àbcéfg"

暫無
暫無

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

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