Search code examples
pythonstdinsys

How do extract multiple words on one line in sys.stdin in Python?


Suppose I have the following:

>>> import sys
>>> a = []
>>> for line in sys.stdin.readline():
...     a.append(line.strip())
... 
hello jerry!
>>> a
['h', 'e', 'l', 'l', 'o', '', 'j', 'e', 'r', 'r', 'y', '!', '']

But I would like to end up with is a list like this:

>>> a
['hello', 'jerry!']

Solution

  • sys.stdin.readline() returns a string not list of lines. So you are iterating over characters of that string not lines. Change your code to this:

    >>> import sys
    >>> a = []
    >>> for word in sys.stdin.readline().split():
    ...     a.append(word)
    ... 
    hello jerry!
    >>> a
    ['hello', 'jerry!']