- Python – Read String from Console
- Examples
- 1. Read a string value from console
- 2. Read multiple strings entered by user in console
- Summary
- How to Read from stdin in Python
- 1. Using sys.stdin to read from standard input
- 2. Using input() function to read stdin data
- 3. Reading Standard Input using fileinput module
- Read from Stdin in Python
- Method 1: Using sys.stdin
- Method 2: Using Python’s Built-In input() function
- Related Question: sys.stdin.readline() and input(): which one is faster when reading lines of input, and why?
- Conclusion
Python – Read String from Console
To read a string from console as input to your Python program, you can use input() function.
input() can take an argument to print a message to the console, so that you can prompt the user and let him/her know what you are expecting.
In this tutorial, we will learn how to use input() function, to read an input from user in your console application.
Examples
1. Read a string value from console
In the following program, we shall prompt the user to enter his name. input() function does print the prompt message to console and waits for the user to enter input.
Python Program
#read string from user firstName = input('Enter your first name: ') print('Hello',firstName)
Run the program. The prompt appears on the console. Type the string and click enter. The new line is considered end of the input and the execution continues with statements after input() statement in the program.
Enter your first name: Brooks Hello Brooks
input() function returns what you have provided as input in the console and you can assign it to a variable. In the above program, we have assigned input() function to a variable. As a result, you can access the string value entered by the user using this variable.
2. Read multiple strings entered by user in console
In this program, we will read multiple strings from user through console, one by one. It is similar to our previous example, but it has two input() statements. The first input() statement shall read a string from console and assign it to firstName. The second input() statement shall read a string from console and assign it to lastName.
Python Program
#read multiple strings from user firstName = input('Enter your first name: ') lastName = input('Enter your last name: ') print('Hello',firstName, lastName)
Run the program, and you shall see the prompt by first input() statement. After you enter some string and type enter, you shall see the prompt by second input() statement. Enter a string for last name and click enter. The program has now read two strings from you, the user.
Enter your first name: Brooks Enter your last name: Henry Hello Brooks Henry
Summary
In this tutorial of Python Examples, we learned to read input from user, specifically to say, read string through console from user, using Python input(), with the help of well detailed Python example programs .
How to Read from stdin in Python
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
1. Using sys.stdin to read from standard input
Python sys module stdin is used by the interpreter for standard input. Internally, it calls the input() function. The input string is appended with a newline character (\n) in the end. So, you can use the rstrip() function to remove it. Here is a simple program to read user messages from the standard input and process it. The program will terminate when the user enters “Exit” message.
import sys for line in sys.stdin: if 'Exit' == line.rstrip(): break print(f'Processing Message from sys.stdin **********') print("Done")
Hi Processing Message from sys.stdin *****Hi ***** Hello Processing Message from sys.stdin *****Hello ***** Exit Done
Notice the use of rstrip() to remove the trailing newline character so that we can check if the user has entered “Exit” message or not.
2. Using input() function to read stdin data
We can also use Python input() function to read the standard input data. We can also prompt a message to the user. Here is a simple example to read and process the standard input message in the infinite loop, unless the user enters the Exit message.
while True: data = input("Please enter the message:\n") if 'Exit' == data: break print(f'Processing Message from input() **********') print("Done")
The input() function doesn’t append newline character to the user message.
3. Reading Standard Input using fileinput module
We can also use fileinput.input() function to read from the standard input. The fileinput module provides utility functions to loop over standard input or a list of files. When we don’t provide any argument to the input() function, it reads arguments from the standard input. This function works in the same way as sys.stdin and adds a newline character to the end of the user-entered data.
import fileinput for fileinput_line in fileinput.input(): if 'Exit' == fileinput_line.rstrip(): break print(f'Processing Message from fileinput.input() **********') print("Done")
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Read from Stdin in Python
Problem Statement: Reading from stdin in Python.
Reading inputs from the user is one of the fundamental building blocks that we learn while learning any programming language. The output of most codes depends on the user’s inputs. Hence, in this article, we are going to learn how to read from stdin in Python.
There are numerous ways to accept the user input in Python. We can either read from the console directly or we can also read from a file specified in the console. Confused? Don’t worry, we got you covered. So, without further delay let’s begin our mission and let’s have a look at the various approaches to read the input from stdin in Python.
Method 1: Using sys.stdin
One way to read from stdin in Python is to use sys.stdin . The sys.stdin gets input from the command line directly and then calls the input() function internally. It also adds a newline ‘\n’ character automatically after taking the input. To remove this newline character you can simply eliminate it using the rstrip() built-in function of Python.
Note: Ensure to import the sys module in your code before utilizing sys.stdin.
Example: In the following snippet, we will use a loop along with sys.stdin that will keep accepting the input from the user till the user wants to terminate the script.
# Importing the sys module import sys print("Enter the input.\n NOTE: To stop execution please enter 'quit'") # Program terminates as soon as user enters 'quit' for line in sys.stdin: if 'quit' == line.rstrip(): break print(f'User Input : ') print("Terminated!")
Enter the input. NOTE: To stop execution please enter 'quit' Hello! Welcome to Finxter! User Input : Hello! Welcome to Finxter! quit Terminated!
Method 2: Using Python’s Built-In input() function
Python’s built-in input() function reads a string from the standard input. The function blocks until such input becomes available and the user hits ENTER. You can add an optional prompt string as an argument to print a custom string to the standard output without a trailing newline character to tell the user that your program expects their input.
# Reading the input from the user i = input("Enter anything: ") print("The Input is: ", i)
Enter anything: Welcome Finxter The Input is: Welcome Finxter
Example 2: Following is another example that reads and processes the input message in the until the user enters the correct input that meets the condition.
while True: # Reading the input from the user i = input("What is the value of 2 + 8") # Only exits when meets the condition if i == '10': break print("The value", i, "is the wrong answer. Try again") print("The value", i, "is the right answer")
Suppose the value insert first is 7 followed by 10. The output will be as follows:
What is the value of 2 + 8 7 7 The value 7 is the wrong answer. Try again What is the value of 2 + 8 10 10 The value 10 is the right answer
Related Video
# Importing the fileinput module import fileinput # You have to feed in the filename as the argument value of the fileinput.input() function. for line in fileinput.input(files = 'demo.txt'): print(line)
This is line 1. Hello and Welcome to Finxter!
Related Question: sys.stdin.readline() and input(): which one is faster when reading lines of input, and why?
import sys # sys.stdin.readline() for i in range(int(sys.argv[1])): sys.stdin.readline() # It takes 0.25μs per iteration. # inut() for i in range(int(sys.argv[1])): input() #It is 10 times slower than the sys.readline().
Conclusion
In this tutorial, we looked at three different methods to read from stdin in Python:
I hope this article has helped to answer your queries. Please subscribe and stay tuned for more interesting articles in the future.
- One of the most sought-after skills on Fiverr and Upwork is web scraping. Make no mistake: extracting data programmatically from websitesis a critical life skill in today’s world that’s shaped by the web and remote work.
- So, do you want to master the art of web scraping using Python’s BeautifulSoup?
- If the answer is yes – this course will take you from beginner to expert in Web Scraping.
I am a professional Python Blogger and Content creator. I have published numerous articles and created courses over a period of time. Presently I am working as a full-time freelancer and I have experience in domains like Python, AWS, DevOps, and Networking.
Be on the Right Side of Change 🚀
- The world is changing exponentially. Disruptive technologies such as AI, crypto, and automation eliminate entire industries. 🤖
- Do you feel uncertain and afraid of being replaced by machines, leaving you without money, purpose, or value? Fear not! There a way to not merely survive but thrive in this new world!
- Finxter is here to help you stay ahead of the curve, so you can keep winning as paradigms shift.
Learning Resources 🧑💻
⭐ Boost your skills. Join our free email academy with daily emails teaching exponential with 1000+ tutorials on AI, data science, Python, freelancing, and Blockchain development!
Join the Finxter Academy and unlock access to premium courses 👑 to certify your skills in exponential technologies and programming.
New Finxter Tutorials:
Finxter Categories: