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 –
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() returns string value. Then, we are getting first character of string value using .
Finally, input() 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() 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,
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)
- import sys imports sys module to python program.
- c = sys.stdin.read(1) reads first character from console and store it in variable c.
- 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.