Python: Why does write use extra blank lines when using write ()?

Note the following Python 3.x code:

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()

      

The result looks like this:

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

      

Why are these blank lines in between?

OK - the real intention to create something like the FancyWriter class was to actually create a write class for Excel: I need to write out tabbed text strings to Excel cells, every row in an Excel row, and every tab-delimited substring to the cells of that row. The strange thing is that in this ExcelWriter class (which also has a write () function as above, just that the print () call is replaced by setting the value of the cells), a similar phenomenon occurs - there are empty lines, for example, in the FancyWriter classes above! (I have a target cell moving one line below if the last character of the incoming line was "\ n".)

Can anyone explain this? What is actually going on between the lines, literally?

And what would be the "most pythonic way" for a FancyWriter (output? File?) Class with a write function to get the desired output like

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

      

Many thanks!

+3


source to share


1 answer


Your "blank lines" is your string function '\n'

to handle the end of the line. For example, if we change the seal to

print(repr(string))

      

and change the line hello world

to

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

      



we see that

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

      

Basically, it print

doesn't build a string and then add a value to it end

, it just passes it on end

to the writer himself.

If you want to avoid this, you will have to avoid print

, I think, a special case for your writer to handle the case of receiving a certain (say, empty) argument, because it looks like it print

will pass end

even if it is an empty string.

+3


source







All Articles