Lesson 16: Sequences, number operations and string operations
A sequence is an ordered collection you can index, slice and loop over. Strings are sequences of characters, which is why the same tools — len(), slicing, in — work on text and on numbers alike.
In short
- A sequence keeps its items in order and supports indexing, slicing, `len()` and looping.
- Indexes start at 0; a negative index counts from the end, so `text[-1]` is the last character.
- A slice `text[1:4]` takes characters 1, 2 and 3 — the stop position is excluded.
- `text[::-1]` reverses a string, which is the shortest palindrome test in Python.
- Strings never change in place: every string method returns a new string.
0
first index of every Python sequence
Python docs
2
built-ins that summarise numbers: min() and max()
Python docs
What a sequence is
A sequence is an ordered collection of items. Python's sequences are strings, lists, tuples and ranges. They share four abilities: you can take one item by position, take a slice of several, ask for the length, and loop over the items.
text = "Python"
print(text[0]) # P
print(text[-1]) # n
print(text[0:3]) # Pyt
print(len(text)) # 6
Number operations
Numbers are not sequences, but a few built-in functions summarise a collection of them:
marks = [40, 7, 91, 12]
print(sum(marks), max(marks), min(marks)) # 150 91 7
print(len(marks)) # 4
print(abs(-17), round(3.567, 2), divmod(17, 5)) # 17 3.57 (3, 2)
String operations, in one program
# strings.py — the methods you will use most
text = " Python makes text easy "
print(len(text)) # 26, spaces included
print(text.strip()) # removes the spaces at both ends
print(text.strip().upper()) # PYTHON MAKES TEXT EASY
print(text.replace("easy", "readable").strip())
print(text.strip().split()) # ['Python', 'makes', 'text', 'easy']
print("-".join(["a", "b", "c"])) # a-b-c
print(text.count("a")) # 2
print(text.find("makes")) # 9
print(text.strip().startswith("Python")) # True
word = "madam"
print(word == word[::-1]) # True: reversed text matches
How it works, step by step
len(text)counts characters, including the spaces on both sides.strip()returns a new string without the leading and trailing spaces. It does not changetext.- Methods chain left to right:
text.strip().upper()strips first, then upper-cases the result. replace()swaps every occurrence and returns a new string.split()breaks the text at spaces and returns a list of words;join()does the reverse.count()andfind()report on content: how many times, and at which position (-1 if absent).word[::-1]is a slice with no start, no stop and a step of -1, so it walks the string backwards.
What it prints
26 Python makes text easy PYTHON MAKES TEXT EASY Python makes text readable ['Python', 'makes', 'text', 'easy'] a-b-c 2 9 True True
The methods worth memorising
| Method | Does |
|---|---|
len(s) | Count of characters |
s.upper(), s.lower() | Change case |
s.strip() | Remove spaces at both ends |
s.replace(a, b) | Swap one piece of text for another |
s.split(sep) | Text to a list |
sep.join(list) | List to text |
s.find(x) | Position of x, or -1 |
s.count(x) | How many times x appears |
s.startswith(x) | True when the text begins with x |
Common mistakes
- Expecting
strip()to change the variable. Writetext = text.strip()if you want to keep the result. - Assuming an index beyond the end returns something. It raises
IndexError. - Slicing
[1:4]and expecting four characters. The stop position is excluded, so it gives three.
Practice
Try these before moving on. Each one uses only what this lesson covered.
- Program 11: check whether a word or number is a palindrome.
- Program 12: use at least six string functions on one sentence and print each result.
- Count the vowels in a sentence with a loop and the `in` operator.
- Print the first three and last three characters of your full name.
Sources
Frequently asked questions
What is a sequence in Python?
An ordered collection whose items can be reached by position: strings, lists, tuples and ranges. All support indexing, slicing, len() and looping.
What is the difference between find() and index() on strings?
find() returns -1 when the text is absent. index() raises ValueError instead. Use find() when absence is normal, index() when it is a bug.
How do I reverse a string in Python?
Slice it with a step of -1: text[::-1]. There is no reverse() method on strings because strings cannot be changed in place.
Why does slicing exclude the stop index?
Because it makes the arithmetic predictable: text[0:3] always has three characters, and text[a:b] has b - a. It is the same rule for range().