LoginSignup
3
5

More than 3 years have passed since last update.

Python3標準入力まとめ

Last updated at Posted at 2019-07-22

はじめに

未来電子テクノロジーでインターンをしている<小栗>です。
「プログラミング初心者であるため、内容に誤りがあるかもしれません。
もし、誤りがあれば修正するのでどんどん指摘してください。

Hackerrank等で使用される標準入力

現在インターン先では、Pythonの学習カリキュラムでHackerRankが使用されています。
そこで、多くの問題で自分が理解に苦しんだ標準入力についてまとめます。

【大前提】input()関数は文字列でデータを取得する

何らかの入力が必要だと判断し、input()関数を使用することが多いのですが、大前提としてinput()関数はデータを文字列で取得します。

文字列のまま取得し、文字列で出力

s1 = input() #文字列で取得し、
print(s1) #文字列のまま出力

s1 = input().strip() #strip()で前後の空白を取り除く

整数を取得する

i1 = int(input()) #文字列で取得し、int()に入れ整数として扱う

複数入力(文字列)を一行で取得し、出力する

#入力:str1 str2

s = input().split() #str1 str2をsplit()で分割して取得し、sに値を入れる、split(','),split('/')はぞれぞれ,/で複数要素を分割
print(s) #出力:['str1', 'str2']
print(s[0]) #出力:str1
print(s[1]) #出力:str2

複数入力(整数)を一行で取得し、出力する

#入力:int1 int2

i = list(map(int, input().split())) #int1 int2を取得し、iに値を入れる。イテレータをlist化している。
print(i[0]) #出力:int1
print(i[1]) #出力:int2

map関数に関して

複数行の入力を取得し出力

単純に行数分の入力を繰り返せば良いので、for文で繰り返す。

#入力:
str1
str2
str3

s = [input() for i in range(3)] #繰り返し
print(s) #出力['str1', 'str2', 'str3']

数値を取得する場合も今までと同様にint()にinput()を入れる。

入力回数を取得し、その回数分値を取得し出力


#入力:
N
str1
str2
str3
.
.
.
strN

N = int(input()) #1行目のNを取得する
s = [input() for i in range(N)] #N回input()を繰り返す
print(s) #出力:['str1', 'str2', 'str3', 'strN']
3
5
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
5