⊗pyPmSlPRS 77 of 208 menu

Slicing a Range of Positions in Python

To get a slice, you need to specify a range of positions for it - from the beginning to the end. In this case, we set the initial index to the left of the colon, and the final index to the right:

txt = 'abcde' res = txt[1:3] print(res) # 'bc'

Given a string:

txt = '12345'

Get a slice of all its characters except the first and last:

'234'

Given a list:

lst = [1, 2, 3, 4, 5, 6, 7]

Get the following slice from it:

[1, 2, 3]

Given a list:

lst = [1, 2, 3, 4, 5, 6, 7]

Get the following slice from it:

[2, 3, 4, 5]

Given a list:

lst = [1, 2, 3, 4, 5, 6, 7]

Get the following slice from it:

[2, 3, 4, 5, 6]
byenru