• Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard
CSEstack

What do you want to Learn Today?

  • Programming
    • Tutorial- C/C++
    • Tutorial- Django
    • Tutorial- Git
    • Tutorial- HTML & CSS
    • Tutorial- Java
    • Tutorial- MySQL
    • Tutorial- Python
    • Competitive Coding Challenges
  • CSE Subject
    • (CD) Compiler Design
    • (CN) Computer Network
    • (COA) Computer Organization & Architecture
    • (DBMS) Database Management System
    • (DS) Data Structure
    • (OS) Operating System
    • (ToA) Theory of Automata
    • (WT) Web Technology
  • Interview Questions
    • Interview Questions- Company Wise
    • Interview Questions- Coding Round
    • Interview Questions- Python
    • Interview Questions- REST API
    • Interview Questions- Web Scraping
    • Interview Questions- HR Round
    • Aptitude Preparation Guide
  • GATE 2022
  • Linux
  • Trend
    • Full Stack Development
    • Artificial Intelligence (AI)
    • BigData
    • Cloud Computing
    • Machine Learning (ML)
  • Write for Us
    • Submit Article
    • Submit Source Code or Program
    • Share Your Interview Experience
  • Tools
    • IDE
    • CV Builder
    • Other Tools …
  • Jobs

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

Aniruddha Chaudhari/149580/31
CodePython

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!

Python Interview Questions eBook

Python
Aniruddha Chaudhari
I am complete Python Nut, love Linux and vim as an editor. I hold a Master of Computer Science from NIT Trichy. I dabble in C/C++, Java too. I keep sharing my coding knowledge and my own experience on CSEstack.org portal.

Your name can also be listed here. Got a tip? Submit it here to become an CSEstack author.

Comments

  • Reply
    Madhumaya
    April 15, 2019 at 1:27 pm

    Hi Aniruddha

    I guess we missed a parenthesis in the last line

    import sys
    msg = sys.stdin.readlines()
    print msg
    • Reply
      Aniruddha Chaudhari
      April 15, 2019 at 6:12 pm

      Hi Madhumaya,

      With the latest version of Python (Python 3), we have to give parenthesis in print statement.

      Updated. Thanks!

  • Reply
    Madhumaya
    April 15, 2019 at 1:34 pm

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

    • Reply
      Aniruddha Chaudhari
      April 15, 2019 at 6:20 pm

      Madhumaya, If you are using Window system, have you tried both ctrl+z and ctrl+d?

    • Reply
      Alan
      March 26, 2020 at 1:26 pm

      Use Shift + Enter for windows. It worked for me.

  • Reply
    Manjunath Angadi
    August 28, 2019 at 5:12 pm
    import sys
    msg = sys.stdin.readlines()
    str=""
    for x in msg:
        str+=x
    newls=list(map(int,str.splitlines()))
    print(newls)
    • Reply
      Aniruddha Chaudhari
      September 1, 2019 at 9:16 am

      Your program is to create a list from the user input values. Good use of map() function.

    • Reply
      Anon
      February 16, 2020 at 6:08 pm

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

  • Reply
    Amey
    September 26, 2019 at 10:47 am

    band kaise krna h isko

    • Reply
      Aniruddha Chaudhari
      September 26, 2019 at 8:01 pm

      What OS you are using?

      Try if ctrl+z or ctrl+d works for you.

      • Reply
        Sumit Jain
        October 1, 2019 at 10:20 am
        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

        • Reply
          Aniruddha Chaudhari
          October 1, 2019 at 6:41 pm

          Sumit, sys.stdin is used to take the input from interpreter console. It will not work with Jupyter.

      • Reply
        Mavis
        January 28, 2020 at 7:09 am

        Hello,

        same scenario here. I am using Vs Code ctrl + d or ctrl + z does not work.

        • Reply
          Aniruddha Chaudhari
          January 28, 2020 at 10:24 am

          Hi Mavis,

          Can you try running it through the command-prompt/terminal?

  • Reply
    Wendell
    March 9, 2020 at 2:41 pm

    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?

  • Reply
    Coder
    April 28, 2020 at 4:32 am

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

    • Reply
      Aniruddha Chaudhari
      April 28, 2020 at 8:32 am

      That’s a disadvantage.

  • Reply
    Jires
    April 29, 2020 at 5:04 am

    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.

  • Reply
    Unen Godswill
    May 23, 2020 at 4:16 pm

    How do thwy get pictures in python and videos from user?

    • Reply
      Aniruddha Chaudhari
      May 24, 2020 at 8:44 am

      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.

  • Reply
    Ascharya Chandupatla
    May 24, 2020 at 12:33 am

    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?

    • Reply
      Aniruddha Chaudhari
      May 24, 2020 at 8:37 am

      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.

  • Reply
    Daniel Hazelton
    July 7, 2020 at 8:14 pm

    In Windows IDLE (Py3.65) you have to press Return then CTR-D.

  • Reply
    Velagala Spandana
    September 7, 2020 at 10:11 am

    How can we take n line input in competitive exams and convert it into the list?

    • Reply
      Aniruddha Chaudhari
      September 16, 2020 at 10:47 pm

      In competitive exams, you will be provided with the list of inputs.

  • Reply
    Apoorva
    October 8, 2020 at 9:21 pm

    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!

    • Reply
      Martan
      January 19, 2021 at 11:25 pm
      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))
      
  • Reply
    Tim
    February 5, 2021 at 7:32 pm

    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.

    • Reply
      Aniruddha Chaudhari
      February 10, 2021 at 9:20 am

      This works with the Python interpreter console and does not work with any Python IDE.

  • Reply
    Swapnil
    September 27, 2021 at 4:11 pm

    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

    • Reply
      Aniruddha Chaudhari
      September 29, 2021 at 9:06 am

      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 Cancel reply

Basic Python Tutorial

  1. Python- Tutorial Overview
  2. Python- Applications
  3. Python- Setup on Linux
  4. Python- Setup on Windows
  5. Python- Basic Syntax
  6. Python- Variable Declaration
  7. Python- Numeric Data Types
  8. Python- NoneType
  9. Python- if-else/elif
  10. Python- for/while else
  11. Python- User Input
  12. Python- Multiline User Input
  13. Python- String Formatting
  14. Python- Find Substring in String
  15. Python- Bitwise Operators
  16. Python- Range Function
  17. Python- List
  18. Python- List Vs Tuple
  19. Python- Compare Two Lists
  20. Python- Sorting List
  21. Python- Delete Element from List
  22. Python- Dictionary
  23. Python- ‘is’ vs ‘==’
  24. Python- Mutable vs Immutable
  25. Python- Generator & Yield
  26. Python- Fibonacci Generator
  27. Python- Assert Statement
  28. Python- Exception Handling 
  29. Python- RegEx
  30. Python- Lambda Function
  31. Python- Installing Modules
  32. Python- Important Modules
  33. Python- Find all Installed Modules
  34. PyCharm- IDE setup
  35. Python- File Handling
  36. Python- Monkey Patching
  37. Python- Decorators
  38. Python- Instance vs Static vs Class Method
  39. Python- Name Mangling
  40. Python- Working with GUI
  41. Python- Read Data from Web URL
  42. Python- Memory Management
  43. Python- Virtual Environment
  44. Python- Calling C Function

Python Exercise

  1. Python- Tricky Questions
  2. Python- Interview Questions (60+)
  3. Python- Project Ideas (45+)
  4. Python- MCQ Test Online
  5. Python- Coding Questions (50+)
  6. Python- Competitive Coding Questions (20+)

Python String

  1. Reverse the String
  2. Permutations of String
  3. Padding Zeros to String/Number

Python List

  1. Randomly Select Item from List
  2. Find Unique Elements from List
  3. Are all Elements in List Same?

Python Dictionary

  1. Set Default Value in Dictionary
  2. Remove all 0 from a dictionary

File Handling

  1. Python- Read CSV File into List
  2. Check if the File Exist in Python
  3. Find Longest Line from File

Compilation & Byte Code

  1. Multiple Py Versions on System
  2. Convert .py file .pyc file
  3. Disassemble Python Bytecode

Algorithms

  1. Sorting- Selection Sort
  2. Sorting- Quick Sort

Other Python Articles

  1. Clear Py Interpreter Console
  2. Can I build Mobile App in Python?
  3. Extract all the Emails from File
  4. Python Shell Scripting

© 2022 – CSEstack.org. All Rights Reserved.

  • Home
  • Subscribe
  • Contribute Us
    • Share Your Interview Experience
  • Contact Us
  • About
    • About CSEstack
    • Campus Ambassador
  • Forum & Discus
  • Tools for Geek
  • LeaderBoard