【Python】 Python ~ 基本編 / スライス操作 ~

■ はじめに

https://dk521123.hatenablog.com/entry/2019/12/17/225829

の Python の資格勉強で、
スライスに関する理解がいまいちだったので
まとめてみる。

■ スライス

* シーケンス型オブジェクト(※)を指定した箇所で切り取って
 コピーを返してくれる機能
 => あくまで「コピー」で実体ではない
  (その証拠として「value[10] = "a"」はエラー)

※ シーケンス型オブジェクト

1) 文字列
2) リスト
3) タプル
4) レンジ

構文

[start:end:step] のように値が指定できる

使用上の注意

* 指定するインデックスは、値と値の間を指す点

value = "HELLO"

# HEL <= 「HELL」ではない
print(value[0:3])

# EL <= 「ELL」ではない
print(value[1:3])

イメージ

+-+-+-+-+-+
|H|E|L|L|O|
+-+-+-+-+-+
0 1 2 3 4 5

■ サンプル

例1:文字列

value = "Hello world!"

# w
print(value[6])

# r
print(value[-4])

# ell <= 注意:「ello」ではない
print(value[1:4])

# Hlowrd
print(value[0:20:2])

# <> <= エラーにはならない
print("<" + value[100:1000] + ">")

# TypeError: 'str' object does not support item assignment
# value[10] = "a"

参考文献
https://qiita.com/tanuk1647/items/276d2be36f5abb8ea52e

関連記事

Python ~ 基本編 / 文字列 ~
https://dk521123.hatenablog.com/entry/2019/10/12/075251
Python ~ 基本編 / リスト ~
https://dk521123.hatenablog.com/entry/2019/10/12/084943
Python ~ 基本編 / リスト・あれこれ ~
https://dk521123.hatenablog.com/entry/2020/11/01/000000
Python ~ 基本編 / 辞書 ~
https://dk521123.hatenablog.com/entry/2019/10/27/100014
Python ~ 基本編 / 辞書・あれこれ ~
https://dk521123.hatenablog.com/entry/2020/10/11/000000
Python ~ 基本編 / タプル・集合 ~
https://dk521123.hatenablog.com/entry/2019/10/26/000000
Python ~ 基本編 / コマンドライン引数 ~
https://dk521123.hatenablog.com/entry/2019/10/11/223651
Python に関する資格
https://dk521123.hatenablog.com/entry/2019/12/17/225829