How to read multiple lines of raw input?

PythonInputUser Input

Python Problem Overview


I want to create a Python program which takes in multiple lines of user input. For example:

This is a multilined input.
It has multiple sentences.
Each sentence is on a newline.

How can I take in multiple lines of raw input?

Python Solutions


Solution 1 - Python

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))

Solution 2 - Python

Alternatively, you can try sys.stdin.read() that returns the whole input until EOF:

import sys
s = sys.stdin.read()
print(s)

Solution 3 - Python

Keep reading lines until the user enters an empty line (or change stopword to something else)

text = ""
stopword = ""
while True:
    line = raw_input()
    if line.strip() == stopword:
        break
    text += "%s\n" % line
print text

Solution 4 - Python

Just extending this answer https://stackoverflow.com/a/11664652/4476612 instead of any stop word you can just check whether a line is there or not

content = []
while True:
    line = raw_input()
    if line:
        content.append(line)
    else:
        break

you will get the lines in a list and then join with \n to get in your format.

print '\n'.join(content)

Solution 5 - Python

Try this

import sys

lines = sys.stdin.read().splitlines()

print(lines)

INPUT:

1

2

3

4

OUTPUT: ['1', '2', '3', '4']

Solution 6 - Python

*I struggled with this question myself for such a long time, because I wanted to find a way to read multiple lines of user input without the user having to terminate it with Control D (or a stop word). In the end i found a way in Python3, using the pyperclip module (which you'll have to install using pip install) Following is an example that takes a list of IPs

import pyperclip
lines = 0

while True:
    lines = lines + 1 #counts iterations of the while loop.
    
    text = pyperclip.paste()
    linecount = text.count('\n')+1 #counts lines in clipboard content.

    if lines <= linecount: # aslong as the while loop hasn't iterated as many times as there are lines in the clipboard.
        ipaddress = input()
        print(ipaddress)

    else:
        break

For me this does exactly what I was looking for; take multiple lines of input, do the actions that are needed (here a simple print) and then break the loop when the last line was handled. Hope it can be equally helpful to you too.

Solution 7 - Python

The easiest way to read multiple lines from a prompt/console when you know exact number of lines you want your python to read, is list comprehension.

lists = [ input() for i in range(2)]

The code above reads 2 lines. And save inputs in a list.

Solution 8 - Python

sys.stdin.read() can be used to take multiline input from user. For example

>>> import sys
>>> data = sys.stdin.read()
  line one
  line two
  line three
  <<Ctrl+d>>
>>> for line in data.split(sep='\n'):
  print(line)

o/p:line one
    line two
    line three

Solution 9 - Python

>Its the best way for writing the code in python >3.5 version

a= int(input())
if a:
    list1.append(a)
else:
    break

even if you want to put a limit for the number of values you can go like

while s>0:
a= int(input())
if a:
    list1.append(a)
else:
    break
s=s-1

Solution 10 - Python

A more cleaner way (without stop word hack or CTRL+D) is to use Python Prompt Toolkit

We can then do:

from prompt_toolkit import prompt

if __name__ == '__main__':
    answer = prompt('Paste your huge long input: ')
    print('You said: %s' % answer)

It input handling is pretty efficient even with long multiline inputs.

Solution 11 - Python

The Python Prompt Toolkit is actually a great answer, but the example above doesn't really show it. A better example is get-multiline-input.py from the examples directory:

#!/usr/bin/env python
from prompt_toolkit import prompt
from prompt_toolkit.formatted_text import HTML


def prompt_continuation(width, line_number, wrap_count):
    """
    The continuation: display line numbers and '->' before soft wraps.
Notice that we can return any kind of formatted text from here.
The prompt continuation doesn't have to be the same width as the prompt
which is displayed before the first line, but in this example we choose to
align them. The `width` input that we receive here represents the width of
the prompt.
    """
    if wrap_count > 0:
        return " " * (width - 3) + "-> "
    else:
        text = ("- %i - " % (line_number + 1)).rjust(width)
        return HTML("<strong>%s</strong>") % text


if __name__ == "__main__":
    print("Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.")
    answer = prompt(
    "Multiline input: ", multiline=True, prompt_continuation=prompt_continuation
)
    print("You said: %s" % answer)

Using this code you get multiline input in which each line can be edited even after subsequent lines are entered. There are some nice additional features, too, such as line numbers. The input is ended by hitting the escape key and then the enter key:

~/Desktop ❯ py prompt.py
Press [Meta+Enter] or [Esc] followed by [Enter] to accept input.
Multiline input: first line of text, then enter
- 2 - second line of text, then enter
- 3 - third line of text, arrow keys work to move around, enter
- 4 - and lines can be edited as desired, until you
- 5 - press the escape key and then the enter key
You said: first line of text, then enter
second line of text, then enter
third line of text, arrow keys work to move around, enter
and lines can be edited as desired, until you
press the escape key and then the enter key
~/Desktop ❯

Solution 12 - Python

How do you like this? I mimicked telnet. The snippet is highly self-explanatory :)

#!/usr/bin/env python3

my_msg = input('Message? (End Message with <return>.<return>) \n>> ')

each_line = ''
while not each_line == '.':
    each_line = input('>> ')
    my_msg += f'\n{each_line}'

my_msg = my_msg[:-1]  # Remove unwanted period.

print(f'Your Message:\n{my_msg}')

Solution 13 - Python

With Python 3, you can assign each line to data:

while data := input():
    print("line", data)

Solution 14 - Python

def sentence_maker(phrase):
    return phrase

results = []
while True:
    user_input = input("What's on your mind: ")
    if user_input == '\end':
        break
    else:
        results.append(sentence_maker(user_input))

print('\n'.join(map(str, results)))

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionfelix001View Question on Stackoverflow
Solution 1 - PythonjamylakView Answer on Stackoverflow
Solution 2 - PythonVenkatView Answer on Stackoverflow
Solution 3 - PythonJunuxxView Answer on Stackoverflow
Solution 4 - PythonRushikesh GaidhaniView Answer on Stackoverflow
Solution 5 - PythonArpitt DesaiView Answer on Stackoverflow
Solution 6 - PythontinkerbitsView Answer on Stackoverflow
Solution 7 - PythonKailiCView Answer on Stackoverflow
Solution 8 - Pythonvishnu vardhanView Answer on Stackoverflow
Solution 9 - PythonДйцрдм МдтнцяView Answer on Stackoverflow
Solution 10 - PythonPratyushView Answer on Stackoverflow
Solution 11 - PythonbobView Answer on Stackoverflow
Solution 12 - PythonyeiichiView Answer on Stackoverflow
Solution 13 - PythonGiovanni CornachiniView Answer on Stackoverflow
Solution 14 - PythonSantosh JhaView Answer on Stackoverflow