在Python 2/3中打印浮动到io.StringIO
我正在尝试编写一个Python程序,该程序可以在Python 2.7和Python 3*中工作。我有一个例子,我使用了在Python 2/3中打印浮动到io.StringIO,python,python-2.7,stringio,Python,Python 2.7,Stringio,我正在尝试编写一个Python程序,该程序可以在Python 2.7和Python 3*中工作。我有一个例子,我使用了StringIO,根据,我所要做的就是使用python3风格的io模块 问题是我正在打印ingfloat到这个StringIO: from __future__ import print_function from io import StringIO with StringIO() as file: print(1.0, file=file) 这导致 TypeErr
StringIO
,根据,我所要做的就是使用python3风格的io
模块
问题是我正在打印ingfloat
到这个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\u literals
启用)时,它可以正常工作
我尝试过的备选方案:
BytesIO
。我不能再打印了,因为“unicode
不支持缓冲区接口”
“{:f}”。格式(…)
everyfloat
。这是可能的,但很麻烦
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应该在文件的顶部),但我个人认为这是合理的。“我看不出print()
的使用已经不再有效了”:为什么这会成为一个问题?为什么不使用file.write()
?顺便说一句:在Python2中使用名为file
的变量是个坏主意,因为它屏蔽了系统提供的函数(与您的问题无关)。为什么不只使用u“{}”。格式化(无论什么)
@cdarke不应该是一种方便吗?难道没有一种方法可以恢复它与StringIO
结合使用的便利性吗?我真的不喜欢有不止一种写入文件的方式,而print
是目前最可读的方式。@Rhymoid:我认为表达式是“TMTOWTDI”(Tim toady):-)map(u{}.format,lst)
至少会让它更简洁一点另一个我采用io.StringIO的原因是:它没有实现\uuuuu退出\uuuu
。为此,我只能尝试
/最后明确地
。@Rymoid:从墙上掉下来,但我想知道py3to2.py是怎么回事?