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
?
Python input() input() returns the string that is given as user input without the trailing newline.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With