본문 바로가기
파이썬/python 문법 & 이론 실습

input() vs sys.stdin.readline()

by Bentist 2022. 3. 7.

Python 3.x에서 input()은 결과적으로 입력 값을 문자열로 받게 된다. 그리고 Python 3.x로 넘어오면서 모든 변수가 객체(object)로 처리됨에 따라서 결과 값도 type에서 class로 바뀌게 되었다.

 

sys.stdin.readline()의 stdin은 standard input을 의미하며, input()과 비슷한 동작을 수행한다. 

input()과 가장 큰 차이점은 input()은 내장 함수로 취급되는 반면, sys에 속하는 메소드들은 file object로 취급된다. 즉, 사용자의 입력만을 받는 buffer를 하나 만들어 그 buffer에서 읽어들이는 것이다.

# Python 3.7
# input()

intInput = input("Integer input : ")
print(type(intInput))

stringInput = input("String input : ")
print(type(stringInput))
# 결과
Integer input : 10
<class 'str'>
String input : python
<class 'str'>

1. input() 내장 함수

parameter로 prompt message를 받을 수 있다. 사용자에게 입력받을 때 "숫자를 입력하세요" 등의 안내 문구가 prompt message이다. 입력받은 값의 개행 문자를 삭제시킨 뒤 리턴한다. 즉 입력받은 문자열에 rstrip() 함수를 적용시켜서 리턴하기 때문에 다소 느리다.

>>> number = input("숫자를 입력하세요: ")
숫자를 입력하세요:

>>> a = input()
hello
>>> a
'hello'

2. sys.stdin.readline()

sys.stdin.readline()은 prompt message를 인수로 받지 않는다.

sys.stdin.readline()은 개행 문자를 포함한 값을 리턴한다. 또한 입력 크기에 제한을 줌으로써 한번에 읽어들일 문자의 수를 정할 수 있다.

 

# 개행 문자 제거 방법

  1. type을 int(정수형)로 바꿔서 개행 문자를 받지 못하도록 하기
  2. 개행 문자를 제거해주는 함수 사용

다음의 함수를 통해 개행 문자를 제거할 수 있다.

rstrip(): 오른쪽 공백을 삭제

lstrip(): 왼쪽 공백을 삭제

strip(): 왼쪽, 오른쪽 공백을 삭제

import sys

a = sys.stdin.readline()
hello
>>> a
'hello\n'

a = sys.stdin.readline(2)
hello
>>> a
'he'
-------------------------------------
>>> a = int(sys.stdin.readline())
5
>>> a
5

>>> a = sys.stdin.readline().rstrip()
hello
>>> a
'hello'

 

댓글