Python Program to Read String as Input (With Example)

In this article, we will learn about how to write python program to read string as input.

We can read string from console in many ways. They are –

  1. Using readline() method from sys module
  2. Using rstrip() method from sys module
  3. Using input() method
  4. Using input() method from fileinput

Using readline() Method From sys Module

readline() method reads one line and return it. We can also define how many byte it can read. That’s how we have used it to read only single character in python. Here, we will see how to read string value using readline() method.

Method 1: read string value using readline()

We can use readline() as shown below –

import sys

str = sys.stdin.readline()
print('Entered value: ', str)

When we run above program, we will get output as shown below –

Hello Tutorialwing!              
Entered value:  Hello Tutorialwing!

First line is user input and second line is output we are printing.

Using rstrip() method from sys module

We can use rstrip() method and sys.stdin to read string in python as below –

import sys

for line in sys.stdin:
    if 'exit' == line.rstrip():
        break
    print(f'Entered value : {line}')

sys.stdin is used to get input from command line. Program is terminated when user enters exit message.

When we run above program, we will get output as below –

hi
Entered value : hi

hello
Entered value : hello

Hello Tutorialwing!
Entered value : Hello Tutorialwing!

exit


...Program finished with exit code 0
Press ENTER to exit console.

Note that there are multiple input from user. For example, hi, hello etc.
Program is terminated when user enters exit text in console.

Using input() method to Read String as Input

String value can be read as user input from console using input() method. It can be done as below –

a=input()

Above program takes input from user and stores in variable a.

Now, notice below program,

a=input()
print("Entered value: ", a)

Above program takes input from user and stores in variable. Then, it prints value to console using print() method.

When we run above program, output is –

Hello
Entered value:  Hello

Using input() method from fileinput to Read String as Input

There is another method using which we can take string input from console in python. We can use input() method from fileinput as below –

import fileinput

for f in fileinput.input():
    print("Entered value: ", f)

When we run above program, we will get output as below –

hi
Entered value:  hi

hello
Entered value:  hello

Hello Tutorialwing!
Entered value:  Hello Tutorialwing!

That’s how we can write python program to read string as input. Visit post to know more in python.

Leave a Reply