0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

input().rstrip().split()でスペースで区切られた入力文字列をリストにして返す

Posted at

input().rstrip().split()についてメモ。
バージョンはPython3.10.6で、引用は公式ドキュメントから。

コード

input = input().rstrip().split()
print(input)

入力

hoge1 hoge2 hoge3

出力

['hoge1', 'hoge2', 'hoge3']

str.rstrip()

rstripは入力文字列の末尾を削除する。ここでは、末尾に意図しない空文字や改行文字が入ってしまった場合にそれを削除するために使用している。

文字列の末尾部分を除去したコピーを返します。引数 chars は除去される文字集合を指定する文字列です。 chars が省略されるか None の場合、空白文字が除去されます。

str.split()

split()は引数をデリミタ文字列として区切った文字列のリストを返す。引数を指定しない場合は空文字で区切られる。デリミタとは、カンマや空白など要素の区切りを表す文字のことを指す。ここでは引数を指定していないので、入力文字列をスペースで区切ったリストが返される。

文字列を sep をデリミタ文字列として区切った単語のリストを返します。

自分がした勘違い

最初このコードを見たとき、inputというクラスがあるのだと勘違いしてそのメソッドとしてrstrip()を探す、みたいな勘違いをしていた。そうではなくて、組込関数input()の戻り値としてstrが返され、そのstrのメソッドとしてrstrip()やsplit()があるようだ。そろそろなんとなく使っていたクラスやメソッドについてもしっかり勉強しなければ。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?