【问题标题】:printing floats to io.StringIO in Python 2/3在 Python 2/3 中将浮点数打印到 io.StringIO
【发布时间】:2016-04-18 15:17:02
【问题描述】:

我正在尝试编写一个可在 Python 2.7 和 Python 3.* 中运行的 Python 程序。我有一个使用StringIO的案例,根据Python-Future's cheatsheet on StringIO,我所要做的就是使用Python 3风格的io模块。

问题是我printing floats 到这个StringIO

from __future__ import print_function
from io import StringIO

with StringIO() as file:
    print(1.0, file=file)

这会导致

TypeError: string argument expected, got 'str'

当我将1.0 替换为u"AAAA"(或"AAAA" 启用unicode_literals)时,它工作正常。

我尝试过的替代方案:

  • BytesIO。我不能再print,因为“unicode 不支持缓冲区接口”。
  • "{:f}".format(...) 每个float。这是可能的,但很麻烦。
  • file.write(...) 而不是 print(..., file=file)。这行得通,但在这一点上,我看不出print() 有什么用处。

还有其他选择吗?

【问题讨论】:

  • 我不认为print() 的使用已经消失了”:为什么会有问题?为什么不使用file.write()?顺便说一句:在 Python 2 中有一个名为 file 的变量是个坏主意,因为它掩盖了系统提供的函数(与您的问题无关)。
  • 为什么不只是u"{}".format(whatever)
  • @cdarke print 不应该是为了方便吗?没有办法恢复它与StringIO结合使用的方便吗?我真的不喜欢有不止一种写入文件的方式,print 是目前最易读的方式。
  • @Rhymoid:我认为表达式是“TMTOWTDI”(Tim-toady):-)
  • map(u"{}".format, lst) 至少会更简洁一些

标签: python python-2.7 stringio


【解决方案1】:

这就是我对这个问题所做的:

import sys

if sys.version_info[0] == 2:  # Not named on 2.6
    from __future__ import print_function
    from StringIO import StringIO
else:
    from io import StringIO

顺便说一下,这破坏了 PEP008(imports 应该在文件的顶部),但我个人认为这是合理的。

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 2013-05-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多