3

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?

0

3 Answers 3

0

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

Sign up to request clarification or add additional context in comments.

Comments

0

I solved the problem in my Debian using this in bash before running the script:

export PYTHONIOENCODING=utf-8

1 Comment

-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.

5 Comments

what if the string is stored in another variable that cannot be edited? For example: string is already stored in STR. how can I add the u?
STR.decode('utf-8') will change it to a unicode object with proper encoding.
tried it. But another error came up: File "/usr/lib/python2.7/encodings/utf_8.py", line 16, in decode return codecs.utf_8_decode(input, errors, True) UnicodeEncodeError: 'ascii' codec can't encode characters in position 23-25: ordinal not in range(128)
@weyhei i think you should encode. STR = STR.encode('utf8')
If you want to clarify what is being asked, go here: stackoverflow.com/questions/9331010/mysql-in-python-encoding

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.