【问题标题】:Unicode problems when using io.StringIO to mock a file使用 io.StringIO 模拟文件时的 Unicode 问题
【发布时间】:2011-04-14 13:14:28
【问题描述】:

我正在使用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。这个问题有更优雅的解决方案吗?

【问题讨论】:

    标签: python unicode stringio


    【解决方案1】:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-12-12
      • 1970-01-01
      • 2020-09-10
      • 2011-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-02
      相关资源
      最近更新 更多