MySQL in Python: UnicodeEncodeError: 'ascii

2019-06-26 09:55发布

问题:

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.