5. Slicing

5.1. Accessing element with index

5.1.1. Accessing element from start

text = 'We choose to go to the Moon!'

text[0]             # 'W'
text[1]             # 'e'
text[23]            # 'M'

5.1.2. Accessing element from back

text = 'We choose to go to the Moon!'

text[-1]            # '!'
text[-5]            # 'M'

5.1.3. Accessing not existing element

text = 'We choose to go to the Moon!'

text[100]           # IndexError: string index out of range

5.2. Accessing range of elements

5.2.1. Accessing slice from start

text = 'We choose to go to the Moon!'

text[0:2]             # 'We'
text[:2]              # 'We'
text[3:9]             # 'choose'
text[23:28]           # 'Moon!'

5.2.2. Accessing slice from back

text = 'We choose to go to the Moon!'

text[-5:]             # 'Moon!'
text[-5:-1]           # 'Moon'
text[:-6]             # 'We choose to go to the'

5.2.3. Accessing slice not existing elements

text = 'We choose to go to the Moon!'

text[:100]            # 'We choose to go to the Moon!'
text[100:]            # ''

5.2.4. Accessing slice from all elements

text = 'We choose to go to the Moon!'

text[:]               # 'We choose to go to the Moon!'

5.2.5. Arithmetic operations on slice indexes

text = 'We choose to go to the Moon!'
lower = 23
upper = 28

text[lower:upper]       # 'Moon!'
text[lower:upper-1]     # 'Moon'

5.3. Slice function

text = 'We choose to go to the Moon!'
range = slice(23, 28)

text[range]           # 'Moon!'

5.4. Reversing and stepping over elements

5.4.1. Every ``n``th element

text = 'We choose to go to the Moon!'

text[::2]             # 'W hoet ot h on'

5.4.2. Reversing

text = 'We choose to go to the Moon!'

text[::-1]            # '!nooM eht ot og ot esoohc eW'
text[::-2]            # '!oMeto go soce'

5.5. Assignments

5.5.1. Slicing text

  1. Z podanych poniżej ciągów znaków
  2. Za pomocą [...] wydobądź Jana III Sobieskiego
  3. Jakie parametry użyłeś dla każdej z linijek?
a = 'UL. Jana III Sobieskiego 1/2'
b = 'ulica Jana III Sobieskiego 1 apt 2'
c = 'os. Jana III Sobieskiego'
d = 'plac Jana III Sobieskiego 1/2'
e = 'aleja Jana III Sobieskiego'
f = 'alei Jana III Sobieskiego 1/2'
g = 'Jana III Sobieskiego 1 m. 2'
h = 'os. Jana III Sobieskiego 1 apt 2'
About:
  • Filename: types_slice.py
  • Lines of code to write: 8 lines
  • Estimated time of completion: 10 min
The whys and wherefores:
 
  • Definiowanie zmiennych
  • Wycinanie elementów stringów
  • Indeksacja elemntów