Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: receive user input including newline characters

I'm trying to read in the following text from the command-line in Python 3 (copied verbatim, newlines and all):

lcbeika
rraobmlo
grmfina
ontccep
emrlin
tseiboo
edosrgd
mkoeys
eissaml
knaiefr

Using input, I can only read in the first word as once it reads the first newline it stops reading.

Is there a way I could read in them all without iteratively calling input?

like image 583
Humphrey Bogart Avatar asked Mar 30 '10 00:03

Humphrey Bogart


People also ask

Does Python input include newline?

Python input() input() returns the string that is given as user input without the trailing newline.

How do I get the input cursor to show on a new line in Python?

In Python, you can specify the newline character by "n". The "" is called the escape character used for mentioning whitespace characters such as t, n and r. Mentioning the newline character using n will bring the cursor to the consecutive line.

How do you take user from next line in Python?

To actually enter the data, the user needs to press the ENTER key after inputting their string. While hitting the ENTER key usually inserts a newline character ( "\n" ), it does not in this case. The entered string will simply be submitted to the application.

How do you take input on the next line?

nextLine() method advances this scanner past the current line and returns the input that was skipped. This method returns the rest of the current line, excluding any line separator at the end. The position is set to the beginning of the next line.


1 Answers

You can import sys and use the methods on sys.stdin for example:

text = sys.stdin.read()

or:

lines = sys.stdin.readlines()

or:

for line in sys.stdin:
    # Do something with line.
like image 72
Mark Byers Avatar answered Oct 06 '22 11:10

Mark Byers