使用io.StringIO模拟文件时的Unicode问题
我在单元测试中使用一个 io.StringIO
对象来模拟一个文件,这个测试是针对一个类的。问题是这个类似乎默认期望所有字符串都是unicode格式的,但内置的 str
并不返回unicode字符串:
>>> buffer = io.StringIO()
>>> buffer.write(str((1, 2)))
TypeError: can't write str to text stream
但是
>>> buffer.write(str((1, 2)) + u"")
6
这样做是可以的。我猜这是因为和unicode字符串拼接后,结果也变成了unicode字符串。有没有更优雅的解决办法呢?
1 个回答
11
io这个包是为了让你的代码在python3.x中能正常运行。在python 3中,字符串默认是unicode格式的。
你的代码在标准的StringIO包下运行得很好,
>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>
如果你想按照python 3的方式来做,就要用unicode()而不是str()。在这里你需要明确地指定。
>>> io.StringIO().write(unicode((1,2)))
6