【发布时间】: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