# 3. Slicing¶

## 3.1. Accessing element with index¶

### 3.1.1. Accessing element from start¶

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

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


### 3.1.2. Accessing element from back¶

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

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


### 3.1.3. Accessing not existing element¶

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

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


## 3.2. Accessing range of elements¶

### 3.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!'


### 3.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'

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

text[4:-2]  # 'hoose to go to the Moo'
text[-5:5]  # ''


### 3.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:]  # ''


### 3.2.4. Accessing slice from all elements¶

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

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


### 3.2.5. Arithmetic operations on slice indexes¶

text = 'We choose to go to the Moon!'
first = 23
last = 28

text[first:last]       # 'Moon!'
text[first:last-1]     # 'Moon'


## 3.3. Slice function¶

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

text[range]           # 'Moon!'


## 3.4. Reversing and stepping over elements¶

### 3.4.1. Every n element¶

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

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


### 3.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'


## 3.5. Assignments¶

### 3.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'

expected = 'Jana III Sobieskiego'
print(f'{a == expected}\t a: "{a}"')
print(f'{b == expected}\t b: "{b}"')
print(f'{c == expected}\t c: "{c}"')
print(f'{d == expected}\t d: "{d}"')
print(f'{e == expected}\t e: "{e}"')
print(f'{f == expected}\t f: "{f}"')
print(f'{g == expected}\t g: "{g}"')
print(f'{h == expected}\t h: "{h}"')

About: The whys and wherefores: Filename: types_slice.py Lines of code to write: 8 lines Estimated time of completion: 10 min Definiowanie zmiennych Wycinanie elementów stringów Indeksacja elemntów