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