Search code examples
encodingutf-8python-3.xstringio

io.StringIO encoding in python3


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.


Solution

  • 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.)