file - Python: Why are there extra blank lines in the output when using write()? -


please consider 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 see here?", file=fw)     print("and here?", file=fw)     return  testfancywriter() 

the output looks following:

<hello world!> < > <how many new lines see here?> < > <and here?> < > 

why these blank lines in between?

ok - real intention creating fancywriter class create writer class excel: need write out tabbed text lines excel cells, each line in excel row, , each tab-separated substring cells of row. strange thing in excelwriter class (which has write() function above, call print() replaced setting cells value), similar phenomenon occurs - there blank rows in fancywriter classes' output above! (i have target cell moving 1 row below, if last character of incoming string '\n'.)

would able explain this? happening between lines, in literal sense?

and 'most pythonic way' fancywriter (output? file?) class write function desired output like

<hello world!> <how many new lines see here?> <and here?> 

thanks lot in advance!

your "blank lines" function being called string '\n', handle end of line. example, if change print to

print(repr(string)) 

and change hello world line to

print("hello world!", file=fw, end="zzz") 

we see

'hello world!' 'zzz' 'how many new lines see here?' '\n' 'and here?' '\n' 

basically, print doesn't build string , add end value it, passes end writer itself.

if want avoid this, you'll have avoid print, think, or special-case writer handle case of receiving (say, empty) argument, because looks print going pass end if it's empty string.


Comments

Popular posts from this blog

c# - Validate object ID from GET to POST -

node.js - Custom Model Validator SailsJS -

php - Find a regex to take part of Email -