Python template for any Input format

Hello Everyone!

[Short and clear] I was working on a Python template that can read any input - irrespective of the input format. Poorly formatted inputs are not uncommon in External contests and that shouldn’t be a problem for Pythonistas. So, I wrote a small script that can handle such inputs.

Here’s the script.

Using stdin and regex modules
# Use this at the very start of the script
from sys import stdin
from re import findall
# Other imports
# Other classes or functions, if any

class IO:
    def __init__(self):
        self.__inputs = findall('[^\n ]+',
        self.__N = len(self.__inputs)
        self.__index = 0

    def has_next(self):
        return self.__index < self.__N

    def next(self):
        self.__index += 1
        return self.__inputs[self.__index - 1]

# Main function or logic

Here’s how you can use it

Basic Usage
io = IO()
for i in range(int(

Code faster using the following style

Referencing style
# input is no longer an inbuilt function
input = IO().next

for test in range(int(input())):
    n = int(input())
    l = []
    for i in range(n):

Basically, the script breaks the input into tokens that match the Regular expression '[^\n ]+'. It matches any character except '\n' and white spaces.

  • Given an Integer N and a sequence of N integers, find the sum of elements of the sequence. There are T test cases. Can your Python solution run perfectly against the following variants of input?
Well formatted
4 1 -2
8 11 12 13 1
Randomly scattered
3 4 
    1    -2   5

    12 13


This is a very basic template I wanted to share. Interested can modify it based on their needs. Also, this cannot be used to read a Sequence of Integers at once, as we can do with the inbuilt input() function.

Note: I am not sure if it works for interactive problems.


Thanks a lot, now I won’t face unnecessary runtime errors in many external contests. :grinning: