【发布时间】:2015-02-04 08:51:08
【问题描述】:
我想检查函数 f1(s) 的参数 s 是否在 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
检查:
MyList2 = [ u"نامشخص" , "test2".encode("utf-8"), u"نامشخص".encode("utf-8") ]
for a in MyList2:
print "Test String = ", a
f1(a)
print "\n\n"
输出:
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 <module>
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 db 收到字符串 s,但我不知道 s 的编码。 有趣的是,对于来自 db f1 的某些字符串 s 错误而没有错误! 似乎 f1 仅适用于某些指定的编码。是否有适用于字符串 s 的所有编码的解决方案?
【问题讨论】:
-
你能发布你的输出和你的测试吗?它对我有用,没有任何问题。