如何在Python中处理Unicode(非ASCII)字符? [英] How to handle Unicode (non-ASCII) characters in Python?

查看:194
本文介绍了如何在Python中处理Unicode(非ASCII)字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Python 中编程,我正在获取信息通过 urllib2 图书馆。问题是,该页面可以为我提供非ASCII字符,例如'ñ''á' urllib2 得到这个字符的时刻,它会引发一个异常,像这样:

I'm programming in Python and I'm obtaining information from a web page through the urllib2 library. The problem is that that page can provide me with non-ASCII characters, like 'ñ', 'á', etc. In the very moment urllib2 gets this character, it provokes an exception, like this:

File "c:\Python25\lib\httplib.py", line 711, in send
    self.sock.sendall(str) 
File "<string>", line 1, in sendall:
    UnicodeEncodeError: 'ascii' codec can't encode character u'\xf1' in position 74: ordinal not in range(128)

我需要处理这些字符。我的意思是,我不想处理该异常,但继续该程序。有什么办法,例如(我不知道这是否是愚蠢的),使用另一个编解码器而不是ASCII?因为我必须使用这些字符,将它们插入数据库等。

I need to handle those characters. I mean, I don't want to handle the exception but to continue the program. Is there any way to, for example (I don't know if this is something stupid), use another codec rather than the ASCII? Because I have to work with those characters, insert them in a database, etc.

推荐答案

插座。如果你想要一个字符串,你必须解码它:

You just read a set of bytes from the socket. If you want a string you have to decode it:

yourstring = receivedbytes.decode("utf-8") 

(替换您用于 utf-8

然后您必须执行相反的操作将其发回:

Then you have to do the reverse to send it back out:

outbytes = yourstring.encode("utf-8")

这篇关于如何在Python中处理Unicode(非ASCII)字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆