Jun Hyuk Kim's Blog
About using sys.stdin vs input in python3 본문
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.
'Coding Problems' 카테고리의 다른 글
| [Python] About round function in python (0) | 2023.09.22 |
|---|---|
| Fixing code in steps and combining (0) | 2022.12.21 |
| Making 2D arrays: Don't use [[0] * arr_len] * arr_len (0) | 2022.12.19 |