Python スライス (slice)
スライスはシーケンスの一部分を切り取ってコピーを取得する。
テキストシーケンスのスライス
+---+---+---+---+---+---+ | P | y | t | h | o | n | +---+---+---+---+---+---+ 0 1 2 3 4 5 6 <- 整数 index -6 -5 -4 -3 -2 -1 <- 負数 index
sequence[index]
>>> str = 'Python' >>> str[3] 'h'
sequence[start:end]
>>> str = 'Python' >>> str[2:4] 'th'
sequence[start:]
>>> str = 'Python' >>> str[2:] 'thon'
sequence[:end]
>>> str = 'Python' >>> str[:4] 'Pyth'
sequence[:]
>>> str = 'Python' >>> str[:] 'Python'
シーケンス型 (sequence)
list() - リスト
tuple() - タプル
range() - range オブジェクト
バイナリシーケンス型
bytes() - バイトオブジェクト
bytearray() - bytearray オブジェクト
memoryview() - メモリビュー
テキストシーケンス型
str() - テキストシーケンス