Reputation: 9200
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
.
Upvotes: 15
Views: 29087
Reputation: 2643
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.
Upvotes: 6
Reputation: 602105
The class io.StringIO
works with str
objects in Python 3. That is, you can only read and write strings from a StringIO
instance. There is no encoding -- you have to choose one if you want to encode the strings you got from StringIO
in a bytes
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.)
Upvotes: 17