How to Read String from Console as Input in Python?
Read String from Console as Input using Python
To read a string from console entered by user as an input in your Python program, you can use input() built-in function.
The input() takes an optional prompt string as an argument to print it to the console for user, so that you user can knows what to enter in the console input.
In this tutorial, you will learn how to use input() function to read a string as an input from user in a Python console application.
Examples
1. Reading a string value from console using input() in Python
In the following program, we have to read user’s first name from standard input and print it to output.
- Call input() function with a prompt
’Enter your first name:’
. input() function reads the string entered by the user in standard input, and returns the string value. - Store the string value in a variable first_name.
- Print the value in first_name using print() function.
Python Program
# Read input string from user
first_name = input('Enter your first name: ')
# Print the read value to output
print(f"Hello {first_name}!")
When the program is run, the prompt appears on the console when program execution is executing input() function. Type the string in the standard output where the prompt appears, and click Enter or Return key. The new line is considered as end of the input, and the execution continues with statements after input() statement in the program.
Output
Enter your first name: Brooks
Hello Brooks!
2. Read multiple strings entered by user in console in Python
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 inputs from user
first_name = input('Enter your first name : ')
last_name = input('Enter your last name : ')
# Print read values to output
print(f"Hello {first_name}, {last_name}")
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.
Output
Enter your first name : Brooks
Enter your last name : Henry
Hello Brooks Henry
Summary
In this tutorial, we learned how to read an input from user, specifically to say, read string through console from user, using Python input(), with the help of well detailed Python example programs .