Multiple lines user Input in Python

avatar

Borislav Hadzhiev

Last updated: Aug 24, 2022

banner

Photo from Unsplash

Multiple lines user Input in Python #

To take multiple lines of user input:

  1. Use a while loop to iterate for as long as the user is typing in values.
  2. On each iteration, append the user input and a newline character to a list.
  3. If the user presses Enter without typing in a value, break out of the loop.
main.py
lines = [] while True: user_input = input() # 👇️ if user pressed Enter without a value, break out of loop if user_input == '': break else: lines.append(user_input + '\n') # 👇️ prints list of strings print(lines) # 👇️ join list into a string print(''.join(lines))

user input multiple lines

We used a while loop to iterate for as long as the user is typing in values.

On each iteration, we check if the user pressed Enter without typing in a value to exit out of the while True loop.

This can be any other condition, e.g. you might have a stop word such as done or quit.

The break statement breaks out of the innermost enclosing for or while loop.

If the user types in a value, we use the list.append() method to append the value and a newline character to a list.

The list.append() method adds an item to the end of the list.

Alternatively, you can use the sys.stdin.readlines() method.

main.py
import sys # 👇️ multiline input using stdin.readlines() # 👇️ User must press Ctrl + D (Unix) or Ctrl + Z to exit print('Press CTRL + D (Unix) or CTRL + Z (Windows) to exit') user_input = sys.stdin.readlines() # 👇️ get list of lines print(user_input) # 👇️ join the list items into a string print(''.join(user_input))

multiple lines input sys stdin readlines

stdin is used for interactive user input.

Note that the user must press CTRL + D (on Unix) or CTRL + Z on Windows to exit.

If you don't want to append a newline character to each item in the list initially, use the str.join() method to join the list items into a string.

main.py
my_list = [] while True: user_input = input() # 👇️ if user pressed Enter without a value, break out of loop if user_input == '': break else: my_list.append(user_input) # 👇️ prints list of strings print(my_list) # 👇️ joins list of strings into a string my_str = '\n'.join(my_list) print(my_str)

input multiple lines

Instead of appending a newline (\n) character to each input, we used the str.join() method to join the list with a newline character separator.

The str.join method takes an iterable as an argument and returns a string which is the concatenation of the strings in the iterable.

main.py
my_list = ['a', 'b', 'c'] my_str = '\n'.join(my_list) # a # b # c print(my_str)

The string the method is called on is used as the separator between the elements.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.