Python iterates over stdin string by string using input ()

I am trying to get several names separated by newlines from the console and put them in a variable. Suppose I want to get input from the terminal forever (I will add code to exit the loop later). I know how to do this with a while loop and recursion, but I would like to be able to do this with a for loop.

In the example below, when I get "peter" as input from the terminal, I get each letter, not a whole line at a time:

 for name in input(): print(name) 

Now, if I use sys.stdin , the name variable becomes "peter\n" :

 for name in sys.stdin: print(name) 

Is there an easy way to get input() to give "name" entire string, rather than single characters? Or just by the nature of using for in will I iterate through the input characters? Are there any inherent risks / problems with getting input this way? Is there a β€œstandard” way to enter data in this situation?

I am using Python 3.5.1 on Ubuntu 15.10.

+5
source share
2 answers

You can wrap stdin to remove newlines; if you can break all trailing spaces (usually good) then this is simple:

 for name in map(str.rstrip, sys.stdin): ... 

You're on Py3, so it works as it is; if you are on Py2 you need to add an import, from future_builtins import map , so you get a lazy map based generator (which gives the lines as they are requested, and does not throw stdin until it ends, and then returns a list all lines).

If you need to limit newlines, a generator expression can do this:

 for name in (line.rstrip("\r\n") for line in sys.stdin): ... 

or with import to allow map push work to level C for (slightly) faster code (a question from 30 to several nanoseconds per line is faster than the xpr gene, but still 40 ns per line is slower than the parameter with no arguments at the top of this answer):

 from operator import methodcaller for name in map(methodcaller('rstrip', '\r\n'), sys.stdin): ... 

Like the first solution, on Py2, be sure to get a map from future_builtins .

+5
source

I would not recommend this to you, but you can create a generator that will be used in a for loop to re-enter lines line by line:

 def getlines(): while True: yield input() for name in getlines(): print(name) ## Remember to break out of the loop at some point 
0
source

Source: https://habr.com/ru/post/1241859/


All Articles