使用io.StringIO模拟文件时出现Unicode问题

Bjö*_*lex 9 python unicode stringio

我正在使用一个io.StringIO对象来模拟一个类的单元测试中的文件.问题是这个类似乎希望默认情况下所有字符串都是unicode,但内置str函数不会返回unicode字符串:

>>> buffer = io.StringIO()
>>> buffer.write(str((1, 2)))
TypeError: can't write str to text stream
Run Code Online (Sandbox Code Playgroud)

>>> buffer.write(str((1, 2)) + u"")
6
Run Code Online (Sandbox Code Playgroud)

作品.我假设这是因为与unicode字符串的串联也会使结果成为unicode.这个问题有更优雅的解决方案吗?

Ivo*_*ijk 9

io包提供了python3.x兼容性.在python 3中,默认情况下字符串是unicode.

您的代码可以使用标准的StringIO包,

>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>
Run Code Online (Sandbox Code Playgroud)

如果你想用python 3方式做,请使用unicode()代替str().你必须在这里明确.

>>> io.StringIO().write(unicode((1,2)))
6
Run Code Online (Sandbox Code Playgroud)