관리 메뉴

Jun Hyuk Kim's Blog

About using sys.stdin vs input in python3 본문

Coding Problems

About using sys.stdin vs input in python3

junhyuk1229 2023. 1. 4. 13:36

Most coding problems use sys.stdin because it is very fast compared to the input function, but there are some changes that people make.

 

1. sys.stdin.readline() takes the '\n' into the string. An addicitonal .rstrip() removes the '\n' character and any extra whitespaces in the end and front. If you want to keep the whitespaces at the end or the front, just pass an argument(.rstrip('\n')).

2. For sys.stdin there is not EOFError. If a EOFError is encountered only a blank string is returned. That is why when trying to use the try/except it will completly ignore that part of the code. A better way of detecting EOFErrors is using a while loop. This has a problem of not being able to distinguish between a empty string and a EOFError.

 

import sys


input_str = sys.stdin.readline()
while input_str:
    input_str = sys.stdin.readline()
    print(input_str)

This code will keep reading lines from the input until an EOFError is detected. If a empty string is detected it will exit too, but when getting user input from a console a '\n' is always added making the error only happen when getting an error.