0
0

【Python】スペース区切りで入力された値を別の変数に入れる

Posted at

文字列の場合

※変数の数は、入力される文字列と同じ数でないと動きません

#文字の場合
a,b = map(str, input().split())
print(a)
print(b)
入力
banana chocolate

aの変数にはbananaが、bの変数にはchocolateが入っています

出力結果
banana      #a
chocolate   #b

整数の場合

#整数の場合
a,b = map(int, input().split())
print(a)
print(b)
入力
123 4

aの変数には123が、bの変数には4が入っています

出力結果
123   #a
4     #b

int(整数)か、str(文字列)を使い分けて、入力する値のデータ型を変えています。

使用例

hoge1,hoge2,hoge3,hoge4 = map(int, input().split())
print(hoge1)
print(hoge2)
print(hoge3)
print(hoge4)
入力
12 3 456 78
出力結果
12   #hoge1
3    #hoge2
456  #hoge3
78   #hoge4
0
0
0

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
0
0