开发者

why in python giving to str func a unicode string will throw an exception?

开发者 https://www.devze.com 2022-12-29 03:34 出处:网络
for example the following: str(u\'לשום\') will thro开发者_开发技巧w an error. how can i prevent these?Calling str() on a unicode is the same as calling .encode(sys.getdefaultencoding()) on it. If

for example the following: str(u'לשום') will thro开发者_开发技巧w an error. how can i prevent these?


Calling str() on a unicode is the same as calling .encode(sys.getdefaultencoding()) on it. If the unicode contains characters that can't be encoded in the default encoding then it will throw a UnicodeEncodeError. The fix is to explicitly encode the unicode in a useful encoding, such as 'utf-8'.


If you're running on Python 3, the u'' notation is a syntax error. Is this your problem? Because in Python <3, your code is absolutely correct, and since 'test' is plain ASCII there are no decoding issues.

0

精彩评论

暂无评论...
验证码 换一张
取 消