请考虑以下 Python 3.x 代码:
class FancyWriter:
def write(self, string):
print('<'+string+'>')
return len(string)+2
def testFancyWriter():
fw = FancyWriter()
print("Hello World!", file=fw)
print("How many new lines do you see here?", file=fw)
print("And here?", file=fw)
return
testFancyWriter()
输出如下所示:
<Hello World!>
<
>
<How many new lines do you see here?>
<
>
<And here?>
<
>
为什么中间有这些空白行?
好的 - 创建类似 FancyWriter 类的真正意图实际上是为 Excel 创建一个编写器类:我需要将选项卡式文本行写入 Excel 单元格,将每一行写入 Excel 行,并将每个制表符分隔的子字符串写入单元格的那一排。奇怪的是,在那个 ExcelWriter 类中(它也有一个像上面一样的 write() 函数,只是对 print() 的调用被设置为单元格值),发生了类似的现象 - 有像 FancyWriter 中的空白行以上类的输出!(如果传入字符串的最后一个字符是'\n',我将目标单元格移动到下一行。)
有人能解释一下吗?从字面上看,字面意思实际上发生了什么?
对于具有写入功能的 FancyWriter(输出?文件?)类来说,获得所需输出的“最 Pythonic 方式”是什么?
<Hello World!>
<How many new lines do you see here?>
<And here?>
提前非常感谢!