python:slice

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'

3. 形式ばらない Python の紹介 - 文字列型 (string) - Python ドキュメント より

list() - リスト
tuple() - タプル
range() - range オブジェクト

bytes() - バイトオブジェクト
bytearray() - bytearray オブジェクト
memoryview() - メモリビュー

str() - テキストシーケンス

  • python/slice.txt
  • 最終更新: 2020/03/28 09:38
  • by ともやん