在 Python 2/3 中打印浮动到 io.StringIO
printing floats to io.StringIO in Python 2/3
我正在尝试编写一个在 Python 2.7 和 Python 3.* 中都有效的 Python 程序。我有一个案例,我使用 StringIO
,根据 Python-Future's cheatsheet on StringIO
,我所要做的就是使用 Python 3-style io
模块。
问题是我 print
ing 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"
(或启用 unicode_literals
的 "AAAA"
)时,它工作正常。
我尝试过的替代方案:
BytesIO
。我不能再 print
,因为“unicode
不支持缓冲区接口”。
"{:f}".format(...)
每 float
。这是可能的,但很麻烦。
file.write(...)
而不是 print(..., file=file)
。这行得通,但在这一点上,我不明白 print()
的用途了。
还有其他选择吗?
这就是我处理这个问题的方法:
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(import
s 应该在文件的顶部),但我个人认为这是合理的。
我正在尝试编写一个在 Python 2.7 和 Python 3.* 中都有效的 Python 程序。我有一个案例,我使用 StringIO
,根据 Python-Future's cheatsheet on StringIO
,我所要做的就是使用 Python 3-style io
模块。
问题是我 print
ing 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"
(或启用 unicode_literals
的 "AAAA"
)时,它工作正常。
我尝试过的替代方案:
BytesIO
。我不能再print
,因为“unicode
不支持缓冲区接口”。"{:f}".format(...)
每float
。这是可能的,但很麻烦。file.write(...)
而不是print(..., file=file)
。这行得通,但在这一点上,我不明白print()
的用途了。
还有其他选择吗?
这就是我处理这个问题的方法:
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(import
s 应该在文件的顶部),但我个人认为这是合理的。