当前位置:   article > 正文

python string utf,比较python中的UTF8字符串

python utf-8 字符串比较

我想检查一下,如果函数f1的argumants在MyList中接收到一些字符串(UTF8格式),则调用函数f2;但我无法正确比较字符串。在def f1( s ):

MyList = [ u"نامشخص".encode("utf-8") , u"Unknow".encode("utf-8")]

for t in MyList:

if( t == s.encode('utf-8') ):

f2()

return None

break

else:

print "Checked strings: ", t , " =?=" , s.encode("utf-8")

print "Checked strings length: ", len(t), " =?=" , len(s)

return s

正在检查:

^{pr2}$

输出:Test String = نامشخص

Here[=]

Test String = test2

Checked strings: نامشخص =?= test2

Checked strings length: 12 =?= 5

Checked strings: Unknow =?= test2

Checked strings length: 6 =?= 5

Test String = نامشخص

Traceback (most recent call last):

File "test.py", line 31, in

f1(a)

File "test.py", line 18, in f1

if( t == s.encode('utf-8') ):

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd9 in position 0: ordinal not in range(128)

事实上,我从sqlite数据库收到字符串s,我不知道s的编码。

有趣的是,对于一些来自dbf1的字符串s却没有出错!

似乎f1只对某些特定的编码有效。有什么解决方案可以对字符串s的所有编码有效吗?在

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/花生_TL007/article/detail/678850
推荐阅读
相关标签
  

闽ICP备14008679号