-
Notifications
You must be signed in to change notification settings - Fork 2.9k
Expand file tree
/
Copy path07_slices.py
More file actions
46 lines (34 loc) · 1.27 KB
/
07_slices.py
File metadata and controls
46 lines (34 loc) · 1.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
"""
Python exposes a terse and intuitive syntax for performing
slicing on lists and strings. This makes it easy to reference
only a portion of a list or string.
This Stack Overflow answer provides a brief but thorough
overview: https://stackoverflow.com/a/509295
Use Python's slice syntax to achieve the following:
"""
a = [2, 4, 1, 7, 9, 6]
# Output the second element: 4:
print('Output the second element: 4:')
print(a[1])
# Output the second-to-last element: 9
print('Output the second-to-last element: 9')
print(a[-2])
# Output the last three elements in the array: [7, 9, 6]
print('Output the last three elements in the array: [7, 9, 6]')
print(a[-3:])
# Output the two middle elements in the array: [1, 7]
print('Output the two middle elements in the array: [1, 7]')
middle = int(len(a)/2)
print(a[middle])
# can't output two in the middle
# Output every element except the first one: [4, 1, 7, 9, 6]
print('Output every element except the first one: [4, 1, 7, 9, 6]')
print(a[1:])
# Output every element except the last one: [2, 4, 1, 7, 9]
print('Output every element except the last one: [2, 4, 1, 7, 9]')
print(a[:-1])
# For string s...
s = "Hello, world!"
# Output just the 8th-12th characters: "world"
print('Output just the 8th-12th characters: "world"')
print(s[7:12])