Wizard
Wizard

Reputation: 22063

sys.stdout.writelines("hello") and sys.stdout.write("hello")

What is the difference between the following two commands?

In [57]: sys.stdout.writelines("hello")                                                                           
hello
In [58]: sys.stdout.write("hello")                                                                                
Out[58]: hello5

Upvotes: 2

Views: 4518

Answers (1)

Mad Physicist
Mad Physicist

Reputation: 114230

sys.stdout.writelines accepts an iterable of strings and writes them to stdout one string at a time. Since it does not append newline characters, elements of the iterable will appear to be concatenated if they don't already contain newlines. The return value is None.

sys.stdout.write accepts a single string, and writes it to stdout. It returns the number of characters written.

The first example (writelines) works because a string is an iterable of strings. Each character in the input is written separately. Notice that there is no Out[57] because the return value is None, but the characters are all printed. They are written individually, but you can't tell because they don't have newlines between them.

The second example (write) prints the whole string all at once. Since write doesn't append newline characters either, the return value (5) is printed immediately after. Out[58] is printed because there is a non-None return value in this case.

In general, writelines was meant to mimic/invert readlines, so normally you could see the difference much better. You would normally call writelines with a list or similar iterable, but write only accepts a single string (and returns a value):

>>> sys.stdout.writelines(['hello\n', 'world\n'])
hello
world

>>> sys.stdout.write('hello\nworld\n')
hello
world
10

Barring the return value, for a single string, the result of writelines and write are indistinguishable. writelines is much less efficient though, since it effectively applies write to each character individually.

Upvotes: 5

Related Questions