2
8

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 5 years have passed since last update.

pythonのスライスの基本

Posted at

はじめに

pythonのスライスについてきちんと理解をするためにまとめます

まず[ ]による抽出

>>> test = 'abcde'
>>>test[0]
'a'
>>> test[4]
'e'
>>> test[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> test[-1]
'e'
>>> test[-5]
'a'
>>> test[-6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

このように[0]~[文字列の長さ-1]までで指定する
マイナスで指定することで末尾から指定することができる

スライスを使う

使い方は[(先頭オフセット):(末尾オフセット):(ステップ)]を使う

>>>test = '0123456789'
>>> #全部抽出
...test[:]
'0123456789'
>>> #5から末尾まで
...test[5:]
'56789'
>>>#3から7まで
...test[3:7]
'3456'
>>>#末尾から5つ取り出す
...test[-5:]
'56789'
>>>#先頭から末尾まで2つごとに取り出す 
...test[::2]
'02468'
>>>#逆順に表示
...test[::-1]
'9876543210'
>>>#100文字目から末尾まで
...test[100:]
''
>>>#末尾の100文字手前から末尾まで
...test[-100:]
'0123456789'

スライスはミスったオフセットでもきちんと動作してくれる
逆順表示はすごく便利

2
8
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
2
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?