MySQL in Python: UnicodeEncodeError: 'ascii'

喜欢而已 提交于 2019-12-12 12:23:44

问题


Hello I am trying to store a string value to MySQL, and i use db.escape_string() so not to escape special characters. The string is

Lala*=#&%@<>_?!:;-'"/()¥¡¿

But when I try to run the code, I get this error:

UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-25: ordinal not in range(128)

What should I do?


回答1:


Try http://pypi.python.org/pypi/Unidecode/0.04.1

For example:

from unidecode import unidecode

your_string = 'Lala*=#&%@<>_?!:;-\'"/()¥¡¿'
unidecode(your_string)

Please note that I've escaped the character ' from your string in order to avoid the SyntaxError




回答2:


The error says that there are characters here which do not exist in ASCII (they are unicode instead) Try using:

newStr = u'Lala*=#&%@<>_?!:;-'"/()¥¡¿'

It needs to be declared as Unicode, with u'something' instead.
This is unlikely to work from most python shells, so make sure your IDE can support unicode, and that the file you are using has a unicode declaration at the top.



来源:https://stackoverflow.com/questions/9330046/mysql-in-python-unicodeencodeerror-ascii

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!