io.StringIO encoding in python3

Giovanni Funchal picture Giovanni Funchal · Feb 20, 2012 · Viewed 15.3k times · Source

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.

Answer

Sven Marnach picture Sven Marnach · Feb 20, 2012

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