4

请考虑以下 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?>

提前非常感谢!

4

1 回答 1

3

您的“空白行”实际上是您使用字符串调用的函数'\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,即使它是空字符串。

于 2015-06-14T13:26:35.763 回答