简体   繁体   中英

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!']

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!']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM