Often only a part of a string is needed, or a list of words must be combined into one line. Slicing, splitting and joining do this.
Slicing
The slice s[start:stop:step] gives the characters from start up to, but not including, stop, moving by step. If start or stop is left out, the slice begins at the first or goes to the last character. A negative step moves backwards, so s[::-1] reverses the string. Slices never cause an index error even if the numbers go beyond the length.
Definition: Slice. A part of a sequence obtained with s[start:stop:step], where the stop index is excluded.
Splitting and Joining
The method split() breaks a string into a list of words, using spaces unless another separator is given. The method join() does the opposite. It is called on the separator and puts the items of a list together, as in "-".join(["a", "b"]), which gives a-b. Together they are used to process lines of text.
Formatting Strings
Besides f-strings, the format() method puts values in the places marked by braces, as in "{} scored {}".format(name, marks). Numbered or named fields such as {0} and {name} allow the order to be changed. Alignment and width can be added, for example {:>8} for right alignment in eight spaces and {:^8} for centring.
Slicing works in the same way on lists and tuples, which are studied in Unit III, so the idea learnt here is used again later. A slice always creates a new object, and the original is not changed. It is also common to combine slicing with the other methods, for example s[:3].upper() to capitalise the first three characters. When a program reads a full name, split() can separate the first and last names, and join() can put them back in a different order for display.
Table 1.6: Slicing the string "PYTHON"
| Expression | Result | Meaning |
|---|---|---|
| s[0:3] | PYT | First three |
| s[-3:] | HON | Last three |
| s[::2] | PTO | Every second |
| s[::-1] | NOHTYP | Reversed |
Example 1.6: Slicing, joining and splitting
Problem: For s = "PYTHON", find s[1:4], s[::-1] and the result of joining the characters with a hyphen. Also split the sentence "learn python well".
Solution:
- s[1:4] takes indices 1, 2 and 3.
- s[::-1] reads from the end.
- "-".join(s) joins the characters, and split() gives a list of words.
Result: The answers are YTH, NOHTYP and P-Y-T-H-O-N, and the sentence gives three words.
s = "PYTHON"
print(s[1:4], s[::-1], s[-3:], s[::2])
print("-".join(s))
words = "learn python well".split()
print(words, len(words))
print("{} scored {:.1f}%".format("Asha", 87.456))
print("{:>8}|{:^8}|".format("ab", "cd"))
Output
YTH NOHTYP HON PTO
P-Y-T-H-O-N
['learn', 'python', 'well'] 3
Asha scored 87.5%
ab| cd |
Common mistakes
- Forgetting that the stop index of a slice is not included.
- Calling join() on the list instead of on the separator string.
- Mixing automatic and numbered fields in the same format string.
Key takeaways
- s[start:stop:step] excludes stop.
- s[::-1] reverses a string.
- split() makes a list and join() builds a string.
- f-strings and format() both insert values into text.
Practice questions
- What does s[::-1] give?
- Which method breaks a string into words?
- What is the result of "-".join(["a", "b", "c"])?
Answers to the practice questions
- The reversed string.
- split().
- "a-b-c".
Sources
- Official BCA syllabus Python Programming, course code 26BCA403SEC01, Unit I
