Reading a line from standard input in Python

Question:

What (if any) are the differences between the following two methods of reading a line from standard input: raw_input() and sys.stdin.readline() ? And in which cases one of these methods is preferable over the other ?

Asked By: Grigor Gevorgyan

||

Answers:

“However, from the point of view of many Python beginners and educators, the use of sys.stdin.readline() presents the following problems:

  1. Compared to the name “raw_input”, the name “sys.stdin.readline()” is clunky and inelegant.

  2. The names “sys” and “stdin” have no meaning for most beginners, who are mainly interested in what the function does, and not where in the package structure it is located. The lack of meaning also makes it difficult to remember: is it “sys.stdin.readline()”, or ” stdin.sys.readline()”? To a programming novice, there is not any obvious reason to prefer one over the other. In contrast, functions simple and direct names like print, input, and raw_input, and open are easier to remember.” from here: http://www.python.org/dev/peps/pep-3111/

Answered By: Mariy

raw_input() takes an optional prompt argument. It also strips the trailing newline character from the string it returns, and supports history features if the readline module is loaded.

readline() takes an optional size argument, does not strip the trailing newline character and does not support history whatsoever.

Since they don’t do the same thing, they’re not really interchangeable. I personally prefer using raw_input() to fetch user input, and readline() to read lines out of a file.

Answered By: Frédéric Hamidi
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.