タプルのスライス機能
【開発環境】
OS:Win10(64ビット)
言語:Python3.8.5(64bit)
Python の統合開発環境:IDLE
IDLEの操作は別サイト参照のこと
【タプルでスライス機能を使用する】
タプルに対してスライス機能(切り取り機能)を使用すると、開始位置から終了位置までの指定した範囲にある要素を含む新しいタプルを取得する事が出来る。
・書式
タプル[開始インデックス:終了インデックス]
・対話コード
Python 3.8.5 (tags/v3.8.5:580fbb0, Jul 20 2020, 15:57:54) [MSC v.1924 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>> animaltuple = ("Cat", "Lion", "Cow", "Dog", "Giraffe")
>>> print(animaltuple[1:4])
('Lion', 'Cow', 'Dog')
>>> print(animaltuple[0:2])
('Cat', 'Lion')
>>> print(animaltuple[2:3])
('Cow',)
>>>
【開始インデックスまたは終了インデックスを省略する】
スライス機能を使用するときに、開始インデックスまたは終了インデックスを省略することができる。
サンプルコード
>>> animaltuple = ("Cat", "Lion", "Cow", "Dog", "Giraffe")
>>> print(animaltuple[:3])
('Cat', 'Lion', 'Cow')
>>> print(animaltuple[2:])
('Cow', 'Dog', 'Giraffe')
>>> print(animaltuple[:])
('Cat', 'Lion', 'Cow', 'Dog', 'Giraffe')
>>>