views:

100

answers:

3

Hello I'm a trying to learn python, In C++ to read in string from stdin I simply do

string str;
while (cin>>str)
    do_something(str)

but in python, I have to use

line = raw_input()

then

x = line.split()

then I have to loop through the list x to access each str to do_something(str)

this seems like a lot of code just to get each string delimited by space or spaces so my question is, is there a easier way?

A: 

There isn't really an "easier" way, since Python doesn't have built-in formatted string functions like C++ does with iostream.

That said, you could shorten your code by combining the operations:

for str in raw_input().split():
   do_something(str)
Dumb Guy
@Dumb, your code would propagate an `EOFError` exception when standard input is done (you really need a `try`/`except` to handle that -- e.g., see my answer). Calling `split` directly on `raw_input()`'s return value, rather than assigning the latter to an intermediate variable, is indeed feasible, but I think that keeping them separated results in more readable code (since you should write a generator for it anyway, saving one line is no big deal IMHO).
Alex Martelli
+1  A: 
map(do_something, line.split())
gnibbler
+3  A: 

Python doesn't special-case such a specific form of input for you, but it's trivial to make a little generator for it of course:

def fromcin(prompt=None):
  while True:
    try: line = raw_input(prompt)
    except EOFError: break
    for w in line.split(): yield w

and then, in your application code, you loop with a for statement (usually the best way to loop at application-code level):

for w in fromcin():
  dosomething(w)
Alex Martelli