How to Read Multiple Lines of Raw Input

How to read multiple lines of raw input?

sentinel = '' # ends when this string is seen
for line in iter(input, sentinel):
pass # do things here

To get every line as a string you can do:

'\n'.join(iter(input, sentinel))

Python 2:

'\n'.join(iter(raw_input, sentinel))

How to get multiline input from the user

In Python 3.x the raw_input() of Python 2.x has been replaced by input() function. However in both the cases you cannot input multi-line strings, for that purpose you would need to get input from the user line by line and then .join() them using \n, or you can also take various lines and concatenate them using + operator separated by \n

To get multi-line input from the user you can go like:

no_of_lines = 5
lines = ""
for i in xrange(no_of_lines):
lines+=input()+"\n"

print(lines)

Or

lines = []
while True:
line = input()
if line:
lines.append(line)
else:
break
text = '\n'.join(lines)

How to read more than one line in an input in Python?

If you wanna read 3 line of input. You can do like this.

inputs = [input() for i in range(3)]

inputs variable will be a list

Python3 best way to read unknown multi line input

The EOFError occurs when you call input(), not when you test it, nor when you print it. So that means you should put input() in a try clause:

try:
line = input()
print(line)
except EOFError:
break

That being said, if input reads from the standard input channel, you can use it as an iterable:

import sys

for line in sys.stdin:
print(line, end='')

Since every line now ends with the new line character '\n', we can use end='' in the print function, to prevent print a new line twice (once from the string, once from the print function).

I think the last version is more elegant, since it almost syntactically says that you iterate over the stdin and processes the lines individually.



Related Topics



Leave a reply



Submit