Python Program to Read Character as Input (With Example)

In this article, we will learn about how to write a python program to read character as input. We will read only single character entered by user and print it to console.

We can use built-in methods to read single character in python. They are –

  1. Using input() method
  2. Using sys.stdin.read() method

Using input() method to Read Single Character in Python

input() method is used to read entered value from console. It returns a string value. To read single character, we can get first value using array index 0 as shown below –

input()[0]

input() returns string value. Then, we are getting first character of string value using [0].
Finally, input()[0] return first character and ignores other characters.

Example 1: Read and print first character using input()

We can print entered first character as below –

a=input()[0]
print("Entered character: ", a)

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

njh
Entered character:  n

Using sys.stdin.read() method to Read Single Character in Python

Using method inside sys module, we can read entered value in console. It is slightly different from input() method. This method reads escape character as well. We can provide a parameter that tells how many character should it read from console. So, if we need to read to only one character, we can pass 1 as argument to this method. For example,

sys.stdin.read(1)

Above line will read one character from console. This is what we are going to use in our program to achieve our target.

Example 1: Read and print Single Character Using sys module

Now, we are going to see how to read and print single character using sys module –

import sys

c = sys.stdin.read(1)

print("Entered character: ", c)

Here,

  1. import sys imports sys module to python program.
  2. c = sys.stdin.read(1) reads first character from console and store it in variable c.
  3. Finally, using print method, we are printing entered value.

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

45
Entered character:  4

Here, 45 is entered value. But, are printing only first character – 4.

That’s how we can write python program to read character as input. Visit link to know more about python.

Leave a Reply