[英]printing floats to io.StringIO in Python 2/3
I'm trying to write a Python program that works in both Python 2.7 and Python 3.*.我正在尝试编写一个适用于 Python 2.7 和 Python 3.* 的 Python 程序。 I have a case where I use
StringIO
, and according to Python-Future's cheatsheet on StringIO
, all I have to to is to use the Python 3-style io
module.我有一个使用
StringIO
,根据Python-Future 关于StringIO
,我所StringIO
就是使用 Python 3-style io
模块。
The problem is that I'm print
ing floats
to this StringIO
:问题是我正在
print
floats
到这个StringIO
:
from __future__ import print_function
from io import StringIO
with StringIO() as file:
print(1.0, file=file)
This results in这导致
TypeError: string argument expected, got 'str'
When I replace 1.0
by u"AAAA"
(or "AAAA"
with unicode_literals
enabled), it works fine.当我用
u"AAAA"
(或启用unicode_literals
"AAAA"
)替换1.0
,它工作正常。
Alternatives I've tried:我尝试过的替代方案:
BytesIO
. BytesIO
。 I can't print
anymore, because " unicode
doesn't support the buffer interface".print
了,因为“ unicode
不支持缓冲区接口”。"{:f}".format(...)
every float
. "{:f}".format(...)
每个float
。 This is possible, but cumbersome.file.write(...)
instead of print(..., file=file)
. file.write(...)
而不是print(..., file=file)
。 This works, but at this point, I don't see what the use of print()
is anymore.print()
的用途了。 Are there any other options?还有其他选择吗?
This is what I do with this issue:这就是我对这个问题所做的:
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
This breaks PEP008 by the way ( import
s should be at the top of the file), but personally I think it is justified.顺便说一下,这打破了 PEP008(
import
应该在文件的顶部),但我个人认为这是有道理的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.