python3中的io.StringIO编码
我似乎找不到 Python3 中 io.StringIO 的默认编码是什么。它是与 stdio
一样的语言环境吗?
我怎样才能改变它?
对于stdio
,似乎只需使用正确的编码重新打开就可以了,但是不存在重新打开StringIO
这样的事情。
I can't seem to find what's the default encoding for io.StringIO
in Python3. Is it the locale as with stdio
?
How can I change it?
With stdio
, seems that just reopening with correct encoding works, but there's no such thing as reopening a StringIO
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
io.StringIO
类与 Python 3 中的str
对象一起使用。也就是说,您只能从StringIO 读取和写入字符串实例。没有编码 - 如果您想在
bytes
对象中对从StringIO
获取的字符串进行编码,则必须选择一种编码,但字符串本身没有编码。(当然,字符串需要在内部以某种编码方式表示。根据您的解释器,该编码是 UCS-2 或 UCS-4,但在使用 Python 时您看不到此实现细节。)
The class
io.StringIO
works withstr
objects in Python 3. That is, you can only read and write strings from aStringIO
instance. There is no encoding -- you have to choose one if you want to encode the strings you got fromStringIO
in abytes
object, but strings themselves don't have an encoding.(Of course strings need to be internally represented in some encoding. Depending on your interpreter, that encoding is either UCS-2 or UCS-4, but you don't see this implementation detail when working with Python.)
正如另一个答案中已经提到的,
StringIO
将(unicode)字符串保存在内存中,因此没有编码。如果您确实需要带有编码的类似对象,您可能需要查看
BytesIO
。如果你想设置标准输出的编码:你不能。至少不是直接的,因为 sys.stdout.encoding 是只写的并且(通常)由 Python 自动确定。 (使用管道时不起作用)
如果您想将具有某种编码的字节字符串写入标准输出,那么您只需使用正确的编码(Python 2)对您打印的字符串进行编码,或者使用 sys.stdout.buffer.write() ( Python 3) 将已编码的字节字符串发送到标准输出。
As already mentioned in another answer,
StringIO
saves (unicode) strings in memory and therefore doesn't have an encoding.If you do need a similar object with encoding you might want to have a look at
BytesIO
.If you want to set the encoding of stdout: You can't. At least not directly since
sys.stdout.encoding
is write only and (often) automatically determined by Python. (Doesn't work when using pipes)If you want to write byte strings with a certain encoding to stdout, then you either just encode the strings you print with the correct encoding (Python 2) or use
sys.stdout.buffer.write()
(Python 3) to send already encoded byte strings to stdout.