Go Beyond
Go Beyond

Reputation: 138

Why is sys.stdout.write outputs unexpected characters?

from sys import stdin, stdout
temp=1
stdout.write(str(temp))

I am expecting output to be 1 but it is 11 . Why?

Upvotes: 4

Views: 775

Answers (1)

sahinakkaya
sahinakkaya

Reputation: 6056

>>> import sys
>>> help(sys.stdout.write)

Help on built-in function write:

write(text, /) method of _io.TextIOWrapper instance
    Write string to stream.
    Returns the number of characters written (which is always equal to
    the length of the string)

The first "1" is the argument that you give to write and the second "1" is length of your string returned by write.

>>> sys.stdout.write("Hello")
Hello5

Note that the return value appears in the output because this is an interactive session. If you run this code from a .py file, you would only see "Hello", as you expected.

Upvotes: 7

Related Questions