2017年3月

python unicode str 常见一个小错误

>>> a=u"你好"
>>> a
u'\u4f60\u597d'
>>> str(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>> import MySQLdb
>>> MySQLdb.escape_string(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-1: ordinal not in range(128)
>>> MySQLdb.escape_string(a.encode("utf8"))
'\xe4\xbd\xa0\xe5\xa5\xbd'

记录一下