Alterna · учебный материал

Indexes and cuts

37.1: Indexes and cuts: Short theory, one example, and Python stepway.

Что в этом материале

Содержание и основные понятия

The first character has an index of 0, the last one is available as -1. The s[left:right] includes left and does not include right.
substance and practice
Grade 8
EEG No. 24
01
How it works.
The string is an orderly unchangeable sequence of characters. The index selects exactly one symbol, and the cut creates a new line from a range.
Index.
The positive index goes to the left of 0; -1 means the last symbol.
Cut.
s[start:stop:step] turns on the Start and does not include the Stop.
Immutability.
Cannot perform s[0] = 'A'; instead create a new line.
Boundaries.
The single wrong index causes IndexError, and the cut is gently cut to the accessible part.
02
One example in execution
Start the short program and go over the lines. The visualiser only shows the code, current line, variables and output.
len(s)
returns the number of symbols, so the last positive index is--
len(s) - 1
The negative step changes direction:
s[::-1]
It's making a turn. The empty line is safe, but
s[0]
In the examination tasks, always read the length limit before direct indexing.
Algorithm map
Read from left to right, then run the code.
1
Start
2
Create row s
3
Take symbol s[1]
4
Take cut s[1:4]
5
Remove Fragments
03
Remember
An empty line requires a separate solution before s[0].
The right border isn't part of the result.
The index -1 only works if the line isn't empty.
Syntax of this page
len(s)
Returns the length of the line or other sequence.
s[i]
Returns one symbol by index; wrong i calls IndexError.
s[start:stop:step]
It returns the cut; the step is not activated and the exit from the border is safely cut off.
s[::-1]
Creates the line backwards.
strip()
Returns the row without blank symbols on the edges.
input()
Reads the line.
print
Fails the values; several arguments share the gap.

Structural map of textbooks