使用io时Unicode出现问题。用StringIO模拟一个文件

时间:2022-03-26 20:27:01

I am using an io.StringIO object to mock a file in a unit-test for a class. The problem is that this class seems expect all strings to be unicode by default, but the builtin str does not return unicode strings:

我用的是io。在类的单元测试中模拟文件的StringIO对象。问题是这个类似乎期望所有的字符串都是默认的unicode,但是内置的str不返回unicode字符串:

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

But

>>> buffer.write(str((1, 2)) + u"")
6

works. I assume this is because the concatenation with a unicode string makes the result unicode as well. Is there a more elegant solution to this problem?

的工作原理。我认为这是因为与unicode字符串的连接也会产生unicode。对于这个问题,有更优雅的解决方案吗?

1 个解决方案

#1


9  

The io package provides python3.x compatibility. In python 3, strings are unicode by default.

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

Your code works fine with the standard StringIO package,

您的代码在标准的StringIO包中运行良好,

>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>

If you want to do it the python 3 way, use unicode() in stead of str(). You have to be explicit here.

如果您希望使用python 3的方式,请使用unicode()而不是str()。这里必须明确。

>>> io.StringIO().write(unicode((1,2)))
6

#1


9  

The io package provides python3.x compatibility. In python 3, strings are unicode by default.

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

Your code works fine with the standard StringIO package,

您的代码在标准的StringIO包中运行良好,

>>> from StringIO import StringIO
>>> StringIO().write(str((1,2)))
>>>

If you want to do it the python 3 way, use unicode() in stead of str(). You have to be explicit here.

如果您希望使用python 3的方式,请使用unicode()而不是str()。这里必须明确。

>>> io.StringIO().write(unicode((1,2)))
6