Dealing with stdin (standard input) in Python

When I started out with competitive programming, I was frequently confused with the usage and implementation of stdin a.k.a. Standard Input in Python.  If you have tried competitive programming, where your code is tested against numerous test cases, you may have come across a similar problem when you started out. So, let’s understand how it works.

In order to understand standard input in Python, first let’s go through 2 other methods, strip() and split().

Let’s take a sample string to test both the methods.

Now let’s apply the split() method on some_string.

As you can see, the split method removes all the spaces and new lines and stores all the words in the string in the form of a list .

Now let’s apply the strip() method on some_string.

Here, the strip method removes all the chars (defaults to blankspace) from the beginning and end of the string.

In order to remove some character other than default blankspace, from the beginning and end of the string, we can specify the character while calling the strip() method as shown below.

We can also combine strip() and split() methods and call them together. But remember, the order in which you call them matters.

As you can see above, calling split() first and then strip() gives an AttributeError because the list object in Python cannot be stripped. The strip() method can be applied to string objects only.

Now, let’s get to the standard input. The standard input can be taken in Python 2.x using raw_input() method. But, the user input may also have extra apces at the beginning or end of the input. Hence, we call the strip() and split() methods on raw_input().

Let’s go to the situation which is most common in competitive programming questions.

Problem 1: The first line of the input contains two integers nm.

Problem 2: The first line of the input contains integer n. The second line contains n inputs in a single array ‘ar’.

Sample Input
2 4 6 8 3

So, we saw how to tackle the problem faced by newbies in competitive programming.


Latest Comments
  1. Arindam Roychowdhury

    If input is as below (in hackerearth), then how to proceed? I am stuck at this.
    result.txt file. You need to read it as standard input not as a file input.

Leave a Reply

%d bloggers like this: