Python:使用write()时,为什么输出中有额外的空行?

时间:2015-06-14 13:18:03

标签: python file python-3.x newline blank-line

请考虑以下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中的空行一样类&#39;输出上面! (如果传入字符串的最后一个字符是&#39; \ n&#39;,我的目标单元格会在下方移动一行。)

有人能解释一下吗?从字面意义上来说,线之间实际发生了什么?

最狡猾的方式是什么&#39;对于FancyWriter(output?file?)类,使用write函数来获得所需的输出,如

<Hello World!>
<How many new lines do you see here?>
<And here?>

提前多多感谢!

1 个答案:

答案 0 :(得分:3)

你的&#34;空白行&#34;实际上是你的函数用字符串'\n'调用,以处理行尾。例如,如果我们将打印更改为

print(repr(string))

并将hello world行更改为

print("Hello World!", file=fw, end="zzz")

我们看到了

'Hello World!'
'zzz'
'How many new lines do you see here?'
'\n'
'And here?'
'\n'

基本上,print没有构建字符串,然后向其添加end值,它只是将end传递给作者本身。

如果你想避免这种情况,你必须避免print,我认为或者特殊情况你的作家要处理接收某个(比如说空的)论证的情况,因为它看起来print将会传递end,即使它是空字符串。

相关问题