What’s the difference between using input() and using sys.stdin.readline()?

Asked

Viewed 60 times

2

What’s the difference between using the input() and use sys.stdin.readline()?

  • 3

    In addition to the differences already mentioned in the answer below, there is also difference when an EOF occurs (for example, when you type Ctrl-D on Linux): input spear one EOFError, while sys.stdin.readline() returns the empty string.

1 answer

3

Straight from the horse’s mouth:

>>> input()
bla
'bla'
>>> input("digite algo: ")
digite algo: bla
'bla'
>>> import sys
>>> sys.stdin.readline()
bla
'bla\n'
>>> sys.stdin.readline(5)
blaaaaaaaaaaaa
'blaaa'

As it turns out, input() does not include the end-of-line character, while the other does. readline() accepts an optional parameter which is the maximum size of the string to be returned.

It seems to me that input() is more appropriate for human interaction while readline() is more targeted when the program will be part of a pipe.

  • 2

    Another difference is that input accepts as a parameter a string that is displayed before asking for data entry

  • @hkotsubo added this case in the example, vlw

Browser other questions tagged

You are not signed in. Login or sign up in order to post.