How to Read Multiline User Input in Python 2 and 3?

How to Read Multiline User Input in Python 2 and 3?

Do you want to ask the user to give input to your Python program?

Taking single line user input data is very easy. You can refer how to take user input from the keyboard.

What about if you want multiline user input?

In Python 2, the raw_input() function is used to take user input.  In Python 3, this function is replaced by the input() function. However, both of these functions do not allow the user to take the multiline input.

Many times we need to take multiline user input in Python whether if it’s for data analysis or data entry for automation.

Now, suppose you have multiple data fields to be filled from the user. Taking user input in a single line does look good. What if you can get user input in multiple lines, just like one field per line.

Let’s do that!

Taking user input for the multiple lines is not difficult in Python. And here is a simple code to get this done…

Code for Reading Multiline User Input in Python

You have to use a function readlines() from the sys library.

Import sys module as it comes inbuilt with Python installation. So, you don’t need to install it explicitly.

import sys
msg = sys.stdin.readlines()
print(msg)

As sys module is present in both Python version 2 and 3, this code works for both Python versions.

How does it work?

Enter your string in multiple lines. Once you complete giving the user input in multiple lines, press ctrl+d. It sends a signalEOF to your system.

If you are a windows user, use ctrl+z instead of ctrl+d. And enter.

User input data will be saved in the variable type list. Each user input line will be saved as the separate elements in the list with a return character.

The best part is- it is not necessary to know the number of lines that you want to read from the user.

After getting the user input, you can write the code to clear the Python console. And then print the data received as user input.

Output of the Program:

[‘I am Python developer\n’,’I know data science\n’,’I am in Love with it\n’]

The user input will be saved in the list data structure. After getting user input in the list (list and tuple in Python), you can iterate the list for each element. Each element represents the one user input line.

Here is code- iterating over each element in the list containing user input.

import sys
msg = sys.stdin.readlines()
print(msg)
for item in msg:
    #manipulate user input data
    print(item)

After reading multiline user input in Python, you can manipulate the data or save it as per your requirement.

Hope this helps you. Any doubt? Write in the comment section.

Happy Pythoning!

31 Comments

  1. Hi Aniruddha

    I guess we missed a parenthesis in the last line

    import sys
    msg = sys.stdin.readlines()
    print msg
  2. Hi Aniruddha

    I am trying this statement in python idle in windows environment .
    “Enter your string in multiple lines. Once you complete giving the user input in multiple lines, press ctrl+d. It sends signalEOF to your system.

    If you are a windows user, use ctrl+z instead of ctrl+d. And enter.”

    But still my console is allowing to enter from keyboards .. why ??

  3. import sys
    msg = sys.stdin.readlines()
    str=""
    for x in msg:
        str+=x
    newls=list(map(int,str.splitlines()))
    print(newls)
    1. That’s unnecessary – check the type of msg. It already is a list.

      If you want to remove the ‘\n’ at the end of every element in the list then you can just use rstrip() method inside a list comprehension.

      And if you want to turn the list into a string, then use “”.join(msg).

      1. import sys
        msg = sys.stdin.readlines()
        print msg
        

        I use this code in jupyter notepad but when I run the code the program executed without taking input from user

  4. Hello,
    It works like a charm. However, after using a simple input() later within the same code I keep received an EOF error. Do you know what the issue could be?

  5. Every time you press enter you cannot go delete it or edit any other line then the one you are typing on

  6. I am using Windows OS, but for EOF I’m trying either ctrl+d or ctrl+z. It doesn’t work even using shift+enter.

    1. If you talking about taking pictures or videos from the user using the command line, you can ask the user to provide a URL to the picture or video and make sure you have access to that URL. If you are talking about Web application, there is way to upload pictures and videos.

  7. Hi,
    how to use this code for limited inputs, let’s say I want to give only 4 words. After entering 4 words it should print the list.
    Can you help me in figuring this?

    1. You can do this. Ask user to enter four words. After taking user input, you can count the number of words. If the count is four, print them. If not, ask the user to input again.

  8. Hi,
    I need to sum integers in each line and print the sum of each line..

    for eg :
    input:
    1 2
    3 4

    output:
    3
    7

    like this, how can I achieve this.?

    Thank you in advance!

    1. import sys
      
      def getSum(line):
          integers = [int(x) for x in line.split(' ')]
          return sum(integers)
      
      def getSums(inp):
          sums = lines = [getSum(line) for line in inp];
          result = ""
          for line in lines:
              result += str(line) + '\n'
          return result
          
      inp = sys.stdin.readlines()
      
      print(getSums(inp))
      
  9. Can you tell me exactly which Python IDE this works with? It doesn’t work with Jupyter or Colab Notebook or Spyder. They do not accept multiline stdin.

  10. Hi Aniruddha,

    First, I want to read 8 lines from STDIN including blank line. Now, I want to search data/input after blank line into the grid data/input before blank line.

    Ex. input :
    AMERICA
    AUSTRIA
    BELGIUM
    IRELAND

    MUR
    AUS
    LAND
    MAD

    1. Hi Swapnil,

      You can loop over input() function to read the country names and save them in the Python list. If your program encounter an empty string, break the loop and then read the search input just like the country names and save them in the Python list. Once you get the list of country names and search data, you can perform any operations as you want.

Leave a Reply

Your email address will not be published. Required fields are marked *