Python slice basics

Introduction

Summarize to get a good understanding of python slices

First, extraction by []

>>> test = 'abcde'
>>>test[0]
'a'
>>> test[4]
'e'
>>> test[5]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range
>>> test[-1]
'e'
>>> test[-5]
'a'
>>> test[-6]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

Specify from [0] to [character string length-1] like this You can specify from the end by specifying with a minus

Use slices

Use [(start offset): (end offset): (step)] to use

>>>test = '0123456789'
>>> #Extract all
...test[:]
'0123456789'
>>> #From 5 to the end
...test[5:]
'56789'
>>>#From 3 to 7
...test[3:7]
'3456'
>>>#Take out 5 from the end
...test[-5:]
'56789'
>>>#Extract every two from the beginning to the end
...test[::2]
'02468'
>>>#Display in reverse order
...test[::-1]
'9876543210'
>>>#From the 100th character to the end
...test[100:]
''
>>>#From the last 100 characters to the end
...test[-100:]
'0123456789'

Slice works fine even with missed offsets Reverse order display is very convenient

Recommended Posts

Python slice basics
Python basics ⑤
Python basics
Python basics ④
Python basics ③
Python basics
Python basics
Python basics
Python basics ③
Python basics ②
Python basics ②
Python slice
Python basics: list
Python basics memorandum
python string slice
#Python basics (#matplotlib)
Python CGI basics
Python basics: dictionary
Basics of Python ①
Basics of python ①
#Python basics (scope)
#Python basics (#Numpy 1/2)
#Python basics (#Numpy 2/2)
#Python basics (functions)
Python array basics
Python profiling basics
Python #Numpy basics
Python basics: functions
#Python basics (class)
Python basics summary
Python basics ② for statement
Python: Unsupervised Learning: Basics
Basics of Python scraping basics
#Python DeepLearning Basics (Mathematics 1/4)
Python basics: Socket, Dnspython
# 4 [python] Basics of functions
Basics of python: Output
[python] Array slice operation
Python
slice
Python and ruby slice memo
python: Basics of using scikit-learn ①
Python basics: conditions and iterations
Slice error in python (´ ; ω ; `)
Paiza Python Primer 4: List Basics
Basics of Python × GIS (Part 1)
Basics of Python x GIS (Part 3)
Paiza Python Primer 5: Basics of Dictionaries
SNS Python basics made with Flask
Getting Started with Python Basics of Python
Slice without using Python, colon (:). a.__getitem__ (slice (3,5)).
Review of the basics of Python (FizzBuzz)
Basics of Python x GIS (Part 2)
Python> What is an extended slice?
About the basics list of Python basics
(python) Deep Learning Library Chainer Basics Basics
Learn the basics of Python ① Beginners
kafka python
Basics of binarized image processing with Python
Python: Basics of image recognition using CNN
python + lottery 6