Python golfers...how are you reading a line from stdin?

Add a reply

Posted by mick 672 days ago:
One thing I'm struggling with is taking data from stdin...I don't know of a way more efficient than this:

import sys
x=sys.stdin.next()

But that means that I've already spent 30 characters to get the line into x, which seems awfully inefficient. If there's a better way to load x from stdin, could somebody give me a hint as to what function or class to look at?

(By the way, I'm just amazed at some of the scores on these problems...I can't wait until there's some policy under which we get to see old code.)
Posted by Mark Byers 671 days ago:
There was a question about input in Python in the Python forum:

http://codegolf.com/boards/conversation/view/92

Currently I use either one of these three methods, depending on the problem:

import sys;a=sys.stdin.read() # Read entire input.

or:

l=raw_input() # Read one line of input.

or:

try:
while 1:l=raw_input();... # Read each line, one at a time. There is a space at the beginning of this line.
except:... # No more input.
Posted by mick 665 days ago:
Thanks muchly for the tips...I especially like the try/while/except loop...and now I'll know to check out the Python forum too!

Add a reply