Why in python giving str func will unicode string throw an exception?

for example the following: st (and 'לשום') throws an error. how can i prevent this?

+2


a source to share


2 answers


The call str()

on is the unicode

same as the call .encode(sys.getdefaultencoding())

on it. If unicode

contains characters that cannot be encoded in the default encoding, then it will throw UnicodeEncodeError

. The fix is ​​to explicitly encode unicode

in a usable encoding eg 'utf-8'

.



+7


a source


If you are using Python 3, the notation u''

is a syntax error. It's your problem? Because in Python <3, your code is absolutely correct, and since the "test" is plain ASCII, there are no decoding problems.



0


a source







All Articles