1
4

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入門(7)~スライス~

Last updated at Posted at 2019-02-18

スライス

スライスとはシーケンスの操作ができる機能です.シーケンスとは複数の要素をまとめて扱える型のことです.pythonのシーケンスには「文字列」,「リスト」,「タプル」などがあります.

スライスは[始めの位置: 終わりの位置: 増加分]というように書くことができます.

また,添字より大きい数字になってもエラーになりません.

文字列に対するスライス

slice.py
a = '123456789'
print(a[2: 4]) #添字の2つ目から4つ目の手前まで
print(a[: 5]) #添字の最初(0)から5つ目の手前まで
print(a[5:]) #添字の5つ目から最後まで
print(a[-2]) #文字列の後ろから2つ目
print(a[:: -1]) #添字全体を後ろから表示
print(a[2: 7: 2]) #添字の2つ目から7つ目の手前まで1つ飛ばしで
実行結果
34
12345
6789
8
987654321
357

リストに対するスライス

slice2.py
a = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(a[2: 7]) #添字の2つ目から7つ目の手前まで
print(a[: 8]) #添字の最初(0)から8つ目の手前まで
print(a[8:]) #添字の8つ目から最後まで
print(a[:]) #全てを表示
print(a[8: 2: -3]) #添字の8つ目から2つ目の手前まで2つ飛ばしで
print(a[2: 7: 2]) #添字の2つ目から7つ目の手前まで1つ飛ばしで
実行結果
[3, 4, 5, 6, 7]
[1, 2, 3, 4, 5, 6, 7, 8]
[9]
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[9, 6]
[3, 5, 7]

最後に

スライスを扱うことによってできることが増えます.スライスを利用してたくさんプログラムを組みましょう.

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?