如何在Python中打印非ASCII字符
当我在 Python 中打印(或写入文件)非 ASCII 字符时遇到问题。我通过重写我自己的对象中的 str
方法并在其中创建“x.encode('utf-8')”解决了这个问题,其中 x 是对象内部的属性。
但是,如果我收到一个第三方对象,并创建“str(object)”,并且该对象内部包含非 ASCII 字符,则会失败。
所以问题是:有没有办法告诉 str
方法该对象通常具有 UTF-8 编码?我正在使用 Python 2.5.4。
I have a problem when I'm printing (or writing to a file) the non-ASCII characters in Python. I've resolved it by overriding the str
method in my own objects, and making "x.encode('utf-8')" inside it, where x is a property inside the object.
But, if I receive a third-party object, and I make "str(object)", and this object has a non-ASCII character inside, it will fail.
So the question is: is there any way to tell the str
method that the object has an UTF-8 codification, generically? I'm working with Python 2.5.4.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
无法让
str()
在 Python 中使用 Unicodestr()
3.0。使用
repr(obj)
而不是str(obj)
。repr()
会将结果转换为 ASCII,正确转义 ASCII 代码范围之外的所有内容。除此之外,使用允许 unicode 的文件对象。因此,不要在输入端进行编码,而是在输出端进行编码:
现在您可以将 unicode 字符串写入
fileObj
,它们将根据需要进行转换。要使print
发生同样的情况,您需要包装sys.stdout
:There is no way to make
str()
work with Unicode in Python < 3.0.Use
repr(obj)
instead ofstr(obj)
.repr()
will convert the result to ASCII, properly escaping everything that isn't in the ASCII code range.Other than that, use a file object which allows unicode. So don't encode at the input side but at the output side:
Now you can write unicode strings to
fileObj
and they will be converted as needed. To make the same happen withprint
, you need to wrapsys.stdout
:您如何使用
unicode(object)
并在您的类上定义__unicode__
方法?然后你就知道了它的 unicode,并且可以按照你想要的方式将其编码到文件中。
How about you use
unicode(object)
and define__unicode__
method on your classes?Then you know its unicode and you can encode it anyway you want into to a file.
我想说,我在Unix系统中找到了一个解决方案,导出一个环境变量,如下:
export LC_CTYPE =“es:ES.UTF-8”
这样,所有文件都是utf-8格式的,所以我可以制作印刷品或其他东西,效果很好
I would like to say that I've found a solution in Unix systems, exporting a environment var, with this:
export LC_CTYPE="es:ES.UTF-8"
This way, all files are in utf-8, so I can make prints or whatever and it works fine
只需将这两行粘贴到代码顶部
请访问此链接了解更多详细信息 https://www.python.org/dev/peps/pep-0263/
just paste these two lines at the top of your code
go to this link for further details https://www.python.org/dev/peps/pep-0263/