Python. Slicing a string (Срезы строк)

11.2.2.2 use slicers to process the string

Python. Slicing a string (Срезы строк)

Strings. Slices

Slices are a very interesting tool Python provides for working with indexed collections.

Slices have their own syntax.
The slice has three parameters, the starting element index START, the ending element index STOP (not including the ending element), and the STEP:

string[START:STOP:STEP]

Several examples with different parameters:

[:]/[::] # all elements,
[::2] # odd elements in order,
[1::2] # even elements in order,
[::-1] # all elements in reverse order,
[5:] # all elements starting from the sixth element,
[:5] # all elements before the sixth element,
[-2:1:-1]
# all elements from the penultimate to the second in reverse order (in all cases of sampling from a larger index to a smaller one, you must specify a step!).

s = "programming"
slice = s[:] # create copy of string
print(slice) # output "programming"
slice = s[:5] 
print(slice) # output "progr"
slice = s[5:]
print(slice) # output "amming"
slice = s[::2]
print(slice) # output "pormig"
slice = s[1::2]
print(slice) # output "rgamn"
slice = s[::-1]
print(slice) # output "gnimmargorp"
slice = s[2:9:3]
print(slice) # output "oai"
slice = s[10:0:-4]
print(slice) # output "gmo"
slice = s[8:15]
print(slice) # output "ing"
slice = s[12::]
print(slice) # output empty string
slice = s[:-5] 
print(slice) # output "progra"
slice = s[-8:-4]
print(slice) # output "gram"

Slice can be used as a value of iterator.

s = "programming"
for i in s[::2]: # iterate over all elements that have even indices in string s
 print(i, end=" ") 
# output "p o r m i g" 

Questions:

Exercises:

Ex. 1 "Determine results of operations"

Категория: Algorithms | Добавил: bzfar77 (15.11.2021)
Просмотров: 3480 | Теги: String, Range, STEP, Slice | Рейтинг: 5.0/2
Всего комментариев: 0
avatar