0

I use python 3.4 and pymysql connection to MySQL DB. I have a select query and then fetchall which returns results into r[]. r[0] is just the first part of the result tuple and its value is an empty string (as it should be based on what is in the DB.)

However, when I use the condition:

if str(r[0]) == ''.encode('utf8'):
        do something...

the condition evaluates to false, instead of what I was expecting it to be true! I test it to figure out why by printing out the values of the part:

    print(str(r[0]))
    print(''.encode('utf8')) 
    print(str(r[0]) == ''.encode('utf8'))  

This prints:

b''
b''
False

Any idea why? This is driving me nuts, because it should not be this hard. What am I missing?

4

1 回答 1

1

您正在比较字节和 unicode,这必然与 Python 3 中的 False 进行比较。一些参考资料:

http://scikit-bio.org/docs/0.1.3/development/py3.html#gotchas

http://lucumr.pocoo.org/2013/7/2/the-updated-guide-to-unicode/

解决方案是不要调用encode()右侧的空字符串:

Python 3.4.2 (default, Oct  8 2014, 10:45:20) 
[GCC 4.9.1] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> str(r[0]) == ''
True

如您所见,encode()onstr对象的结果是字节:

>>> x = ''.encode('utf8')
>>> type(x)
<class 'bytes'>
于 2015-01-14T09:48:30.270 回答