Basics · Lesson 7 of 27
Indexing and slicing
Each character in a string has a position called an index. Counting starts at 0.
p y t h o n 0 1 2 3 4 5 -6 -5 -4 -3 -2 -1
word = "python" print(word[0]) # p first character print(word[3]) # h print(word[-1]) # n negative index counts from the end
Slicing
word[start:end] gives the part from start up to, but not including, end.
print(word[0:3]) # pyt print(word[2:]) # thon (no end = till the end) print(word[:2]) # py (no start = from the beginning) print(word[::-1]) # nohtyp (step -1 = reversed)
Your task
word = "python" is given. Print, one per line:
- the first character
- the last character
- the first three characters
- the whole word reversed