Slicing and string methods: reading the index rules
How start, stop and step work on lists and strings, plus the string methods that clean and format text in scripts.
Slicing questions are the fastest way for a screening to check whether you really know how Python counts. The rules are small, but if you guess instead of applying them you lose easy marks. This lesson gives you the rules, the common string methods, and the mistakes to watch for.
The three-part slice
A slice is written sequence[start:stop:step]. The item at start is included, the item at stop is not, and step says how far to jump. Leaving a part empty means "from the beginning", "to the end" or "step of one". Negative indexes count from the end, so -1 is the last item.
word = "screening"
print(word[0:6]) # screen
print(word[-3:]) # ing
print(word[::2]) # sreig
print(word[::-1]) # gnineercs
nums = [10, 20, 30, 40, 50]
print(nums[1:4]) # [20, 30, 40]
print(nums[:2] + nums[3:]) # [10, 20, 40, 50]
print(nums[10:]) # []Two details catch people. A slice that runs past the end returns an empty list instead of raising an error, while nums[10] on its own raises IndexError. And [::-1] is the standard way to reverse a string, because strings have no reverse() method.
String methods you will use daily
Most script work is cleaning text that came from a file or a form. These methods do the heavy lifting:
line = " Order 1042, shipped "
parts = line.strip().split(", ")
print(parts) # ['Order 1042', 'shipped']
print("-".join(parts)) # Order 1042-shipped
name, total = "Asha", 1234.5
print(f"{name}: {total:.2f}") # Asha: 1234.50
print("2024-05-01".replace("-", "/")) # 2024/05/01
print("Hello World".lower().startswith("hello")) # Truestrip()removes spaces and newlines from both ends only, not from the middle.split()returns a list;join()is called on the separator, not on the list.- f-strings format values in place;
:.2fmeans two decimal places. - Strings never change in place. Every method returns a new string, so
name.upper()alone does nothing unless you assign the result.
Common mistakes and a practice habit
- Thinking the stop index is included.
word[0:6]gives six characters, positions 0 to 5. - Mixing up
word[-3](one character) withword[-3:](the last three). - Calling
", ".join(numbers)on a list of integers.joinneeds strings, so convert first withstr(). - Forgetting that
split()with no argument splits on any run of whitespace, whilesplit(" ")splits on every single space.
Practice habit: Each day, take one short string such as a date, an email address or a product code and write five slices on paper before running them. Predict the output, then check. After a week the index rules stop needing thought, which is exactly what a timed test rewards.
More in Programming