Python String Methods: find, split, join, and strip
Introduction
Python string methods can search a log line, split a shipment record into fields, and join cleaned values into a report. Their edge cases matter: a missing match returns -1 with find, while strip(".csv") treats its argument as a set of characters rather than an exact suffix.
This lesson covers objective 3.3 in the PCAP-31-03 Strings section (18% of the score, 8 of 40 items). You will compare search methods, preserve empty fields where required, use maxsplit, and trace sorting and whitespace cleanup.
Learning objectives
After this lesson you can:
- Locate substrings with
find(),rfind(),index()andrindex(), including the optional start and end arguments, and predict their failure behaviour. - Split text with
split(), with and without a separator and amaxsplitargument, and explain how empty fields appear. - Assemble text from a list of strings with
join()and explain why the separator is the object. - Use
strip(),lstrip()andrstrip()correctly and avoid the "character set" trap when removing a prefix or suffix. - Sort strings with
sorted()and predict the case-sensitive order. - Parse a messy manifest robustly.
Searching: find, rfind, index, rindex, count
The method s.find(sub) returns the lowest index where the substring sub starts, or -1 if it is absent. s.rfind(sub) returns the highest index, again -1 when absent. s.index(sub) and s.rindex(sub) behave the same way but raise ValueError when the substring is missing.
path = "reports/2026/q1/summary.q1.txt"
print(path.find("q1")) # 13
print(path.rfind("q1")) # 24
print(path.find("xyz")) # -1
print(path.index("2026")) # 8
print(path.index("xyz")) # ValueError: substring not found
print(path.count("q1")) # 2All four search methods accept optional start and end arguments that limit the part of the string that is examined, using the same convention as slices (the end is excluded):
text = "banana"
print(text.find("an")) # 1
print(text.find("an", 2)) # 3
print(text.find("an", 4)) # -1
print(text.rfind("an", 0, 4)) # 1
print(text.count("a")) # 3
print(text.count("ana")) # 1, counts non-overlapping matchesThe positions returned are always relative to the whole string, even when a start argument is used. Compare Python string slicing and comparison when deciding which indexes a bounded search may examine. The call text.find("an", 2) returns 3, not 1.
| Method | Direction | If missing | Returns |
|---|---|---|---|
find(sub) |
left to right | -1 |
first index |
rfind(sub) |
right to left | -1 |
last index |
index(sub) |
left to right | ValueError |
first index |
rindex(sub) |
right to left | ValueError |
last index |
count(sub) |
whole string | 0 |
number of non-overlapping matches |
The value -1 is dangerous because it is also a valid negative index. For a non-empty s, s[s.find("x")] silently returns its last character when "x" is absent. For an empty s, the resulting index -1 raises IndexError. When absence should never occur, prefer index(), so that the error is visible. When absence is a normal outcome, use find() and test the result, or use in for a plain yes/no answer.
Worked example: extracting a file extension safely
Problem. Write a function that returns the extension of a file name without the dot, or an empty string when the name has no dot. What does it return for "archive.tar.gz", "README" and ".bashrc"?
Step 1: choose the right search. A file name can contain several dots, and the extension follows the last one. Therefore rfind(".") is the right tool, not find(".").
Step 2: handle absence. When rfind returns -1, there is no dot, and the function should return an empty string.
def extension(name):
pos = name.rfind(".")
if pos == -1:
return ""
return name[pos + 1:]
print(extension("archive.tar.gz")) # gz
print(extension("README")) # (empty string)
print(extension(".bashrc")) # bashrcStep 3: trace. For "archive.tar.gz" the last dot is at index 11, so the slice starts at 12 and returns gz. For "README", rfind returns -1 and the function returns "". For ".bashrc", the dot is at index 0 and the slice returns bashrc.
Solution. The function returns gz, an empty string, and bashrc.
Why other choices are worse. find(".") would return tar.gz for the first name. Using name[name.rfind(".") + 1:] without the test returns the whole name for "README", because -1 + 1 is 0. Using index(".") raises ValueError for names without a dot, which would crash the program on a normal input. (The result for .bashrc follows the simple rule defined here; a production tool might treat a leading dot as part of the name.)
Splitting: split
The method s.split() cuts a string into a list of substrings. It has two very different modes.
With no argument, split() splits on runs of whitespace (spaces, tabs, newlines) and discards empty fields at the beginning and the end:
line = " red green\tblue\n"
print(line.split()) # ['red', 'green', 'blue']
print("".split()) # []
print(" ".split()) # []With a separator, split(sep) cuts at every occurrence of the exact separator and keeps empty fields:
line = "red,,green,blue,"
print(line.split(",")) # ['red', '', 'green', 'blue', '']
print("a b".split(" ")) # ['a', '', 'b']
print("".split(",")) # ['']
print("a--b--c".split("--")) # ['a', 'b', 'c']Notice the difference: "a b".split() gives ['a', 'b'], while "a b".split(" ") gives ['a', '', 'b'] because there is an empty field between the two spaces. Splitting an empty string with a separator returns a list that contains one empty string, but without an argument it returns an empty list. An empty separator raises ValueError.
The optional maxsplit argument limits the number of cuts, which is useful when only the first fields matter and the rest is free text:
entry = "2026-10-19 ERROR disk almost full on node 3"
print(entry.split(" ", 2)) # ['2026-10-19', 'ERROR', 'disk almost full on node 3']
print(entry.rsplit(" ", 1)) # ['2026-10-19 ERROR disk almost full on node', '3']
print(entry.split(maxsplit=1)) # ['2026-10-19', 'ERROR disk almost full on node 3']With maxsplit=2 there are at most three items, and the last one keeps the remaining text intact. Whitespace mode also has a special zero-limit case: " a b ".split(maxsplit=0) gives ['a b '], removing only leading whitespace. The method rsplit() counts from the right. Two related helpers are splitlines(), which cuts at line boundaries, and partition(sep), which always returns a tuple of three items: the part before the first separator, the separator and the part after it.
print("a=b=c".partition("=")) # ('a', '=', 'b=c')
print("abc".partition("=")) # ('abc', '', '')
print("l1\nl2\r\nl3".splitlines()) # ['l1', 'l2', 'l3']Reassembling: join
The method sep.join(items) builds one string from an iterable of strings, placing sep between the items. The separator is the object on which the method is called, which surprises people who expect items.join(sep).
parts = ["red", "green", "blue"]
print(", ".join(parts)) # red, green, blue
print("".join(parts)) # redgreenblue
print("-".join("abc")) # a-b-c
print("/".join(["usr", "bin"]))# usr/bin
print(", ".join([])) # (empty string)Every item must already be a string. A number in the list raises TypeError, so convert first:
nums = [3, 1, 2]
print(",".join(str(n) for n in nums)) # 3,1,2
print(",".join(nums)) # TypeError: sequence item 0: expected str instance, int foundThe pair split and join allows a compact normalisation of whitespace:
messy = " too many\t spaces \n"
print(" ".join(messy.split())) # too many spacesBecause split() without argument removes all runs of whitespace, joining with one space produces a clean line.
join is also the efficient way to build long strings, since it creates the final string once instead of many intermediate strings like repeated +.
Stripping: strip, lstrip, rstrip
The method s.strip() removes characters from both ends of the string. Without an argument it removes whitespace. With an argument, it receives a set of characters, not a prefix or a suffix, and removes any of those characters from the ends until it meets a character that is not in the set.
print(" hi ".strip()) # hi
print("xxhixx".strip("x")) # hi
print("--== title ==--".strip("-=")) # " title " (spaces remain)
print("--== title ==--".strip("-= ")) # title
print("hello".lstrip("he")) # llo
print("hello".rstrip("lo")) # he
print("mississippi".strip("ips")) # mThe last examples show the trap. "hello".lstrip("he") removes h and then e, because both belong to the set, then stops at l. It does not mean "remove the prefix he". The same call on "heel" removes h, e and e, giving l. For "mississippi".strip("ips"), the left stops at m. Every following character belongs to the set {i, p, s}, so stripping from the right removes that entire suffix and leaves m.
To remove an exact prefix or suffix, use removeprefix() and removesuffix() (available since Python 3.9), or a slice after a test:
name = "report_final.txt"
print(name.removesuffix(".txt")) # report_final
print(name.removeprefix("report_")) # final.txt
print("data".removeprefix("xyz")) # data
print("test.py".rstrip(".py")) # test (a surprising but correct result of the set rule)
print("happy.py".rstrip(".py")) # ha (the trailing 'p' and 'y' of 'happy' are removed too)The last example is a classic bug: rstrip(".py") removes any of the characters ., p and y from the right, which also eats the end of happy. The method strip() never touches characters inside the text, only at the ends.
| Method | Removes | Argument meaning |
|---|---|---|
strip(chars) |
both ends | set of characters |
lstrip(chars) |
left end | set of characters |
rstrip(chars) |
right end | set of characters |
removeprefix(p) |
exact prefix once | exact text |
removesuffix(p) |
exact suffix once | exact text |
Worked example: tracing strip with a character set
Problem. What does "[[price: 40]]".strip("[]") return, and what does "[[price: 40]]".strip("[]0 ") return?
Step 1: first call. The set is [ and ]. The left end starts with [[, which are removed. The next character is p, not in the set, so the left side stops. On the right, ]] are removed and the next character is 0, which is not in the set. The result is price: 40.
Step 2: second call. The set now contains [, ], 0 and a space. The left side is the same: [[ removed and p stops it. On the right side, ]] are removed, then 0 is in the set and is removed, then 4 is not in the set, so the right side stops.
Solution. The first call returns price: 40. The second returns price: 4.
Why this matters. The second call shows that the characters of the set can be removed in any order and any number of times while they are at the end of the string. Anyone who thinks the argument is a sequence expects price: 40 for both calls.
Sorting strings
sorted(iterable) returns a new list in ascending order. String order is lexicographic by code point and case-sensitive. Among ASCII characters, digits come before uppercase letters, then lowercase letters. Other Unicode characters follow their code points rather than a language’s collation rules.
names = ["bob", "Alice", "carol", "Bob", "alice"]
print(sorted(names))
# ['Alice', 'Bob', 'alice', 'bob', 'carol']
print(sorted(names, key=str.lower))
# ['Alice', 'alice', 'bob', 'Bob', 'carol']
print(sorted(names, key=len))
# ['bob', 'Bob', 'Alice', 'carol', 'alice']
print(sorted(names, reverse=True)[0])
# carolWith key=str.lower, "Alice" and "alice" compare equal and keep the original order (Alice first in the input), while "bob" appears before "Bob" because it came first. With key=len, strings of the same length (3, then 5) also keep their input order. The key function is called once per item, and the items themselves are returned unchanged.
To sort the characters of a word into a string, join the result: "".join(sorted("banana")) returns aaabnn. Two words are anagrams when their sorted letters match.
Comparing the main text tools
| Task | Best tool | Notes |
|---|---|---|
| does the text contain a substring? | in |
does not check word boundaries |
| where is the word? | find / index |
choose by failure policy |
| cut into fields on a separator | split(sep) |
keeps empty fields |
| cut into words | split() |
ignores repeated whitespace |
| first key and the rest | partition or split(sep, 1) |
missing non-empty separator is a normal result; an empty separator is invalid |
| clean the ends | strip() |
character set |
| remove an exact suffix | removesuffix |
exact text |
| build a line | sep.join(list) |
items must be str |
Tracing drill
row = " 17 ; kettle;; 4 ;"
fields = row.split(";")
print(len(fields))
print([f.strip() for f in fields])
print(row.strip().strip(";").split(";")[-1].strip())
print(row.find(";"), row.rfind(";"), row.find("zzz"))
print("-".join(sorted("cab")))- The row has four semicolons, so there are five fields:
" 17 "," kettle",""," 4 "and"". The length is 5. - Stripping each field gives
['17', 'kettle', '', '4', '']. The empty fields remain, becausesplitwith a separator keeps them. row.strip()removes the leading space. The trailing character is;, so the string ends with it. The secondstrip(";")removes that final semicolon. After splitting, the last field is" 4 ", whose stripped value is4.- The first semicolon is at index 4 (counting the leading space: index 0 is the space,
1and7are indexes 1 and 2, the space is index 3, and the semicolon is index 4). The last semicolon is at the last index, 18. Missing text returns -1. Counting the string" 17 ; kettle;; 4 ;"character by character gives a length of 19, so the output is4 18 -1. sorted("cab")returns['a', 'b', 'c']and the join givesa-b-c.
Mini case study: the shipment manifest
A logistics team receives records in the form ITEM : QUANTITY : DESTINATION. Item and destination must be non-empty, and quantity must convert to a non-negative integer. Extra spaces are allowed, destinations can contain colons, and a later valid duplicate item replaces the earlier value. These simple records have no quoting or escaping rules.
bolts : 120 : Lyon
nuts:80:Paris: Gate 4
washers : Berlin
gasketsTask. Write a parser that returns a dictionary {item: (quantity, destination)} for valid lines and a list of rejected lines. Show the result.
def parse(lines):
good, bad = {}, []
for raw in lines:
parts = [p.strip() for p in raw.split(":", 2)]
if len(parts) != 3 or not parts[0] or not parts[2]:
bad.append(raw.strip())
continue
item, qty, dest = parts
try:
quantity = int(qty)
except ValueError:
bad.append(raw.strip())
continue
if quantity < 0:
bad.append(raw.strip())
continue
good[item] = (quantity, dest)
return good, badSolution by tracing.
" bolts : 120 : Lyon"has two colons, sosplit(":", 2)gives three parts. After stripping:bolts,120,Lyon. The quantity converts to 120. Stored as{"bolts": (120, "Lyon")}."nuts:80:Paris: Gate 4"has three colons, butmaxsplit=2stops after two cuts, so the destination keeps the remaining text:Paris: Gate 4. Stored as{"nuts": (80, "Paris: Gate 4")}. A plainsplit(":")would have produced four fields and lost the structure."washers : Berlin"has only one colon: two parts, solen(parts) != 3and the line is rejected."gaskets"has no colon: one part, rejected.
The result is ({'bolts': (120, 'Lyon'), 'nuts': (80, 'Paris: Gate 4')}, ['washers : Berlin', 'gaskets']).
Two design decisions deserve attention. First, only int(qty) is protected by try/except ValueError; assignment happens after conversion and range validation. See handling conversion errors for the reason to keep that protected region small. Second, the parser reports rejected lines instead of discarding them silently, which lets an operator correct the source.
Common pitfalls and exam tips
findreturns -1,indexraisesValueError. Index-1selects the last character only when the string is non-empty.- Positions are relative to the whole string, even with a
startargument. split()andsplit(" ")are different: the first ignores repeated whitespace, the second keeps empty fields."".split()is[]but"".split(",")is[''].joinis called on the separator and needs strings.strip("abc")removes a set of characters, not the prefixabc.- Check each method’s return type. Search gives an integer,
splitgives a list, andjoingives a string; none mutates the original text. sortedis case-sensitive and returns a list,list.sort()returnsNone.countcounts non-overlapping matches:"aaaa".count("aa")is 2.
Exam tip. When a question gives
stripwith an argument, write the argument as a set of characters first, then walk from each end until a character is not in the set. This single habit resolves most trick questions.
Key terms
- Substring: a contiguous part of a string.
- Separator: text at which
splitcuts and between whichjoinplaces items. - Field: one element produced by a split.
maxsplit: maximum number of cuts.- Character set (of
strip): the characters removed from the ends. - Stable sort: equal keys keep their original order.
Summary checklist
- I can predict the result of
find,rfind,index,countincluding absent text. - I can explain the difference between
split()andsplit(sep). - I can use
maxsplitandpartitionto keep the remaining text. - I can build a line with
joinand convert items to strings first. - I know that
stripworks with a set of characters. - I can remove an exact suffix with
removesuffix. - I can predict the output of
sortedon mixed-case strings.
Official sources
- PCAP-31-03 exam syllabus, objective 3.3: https://pythoninstitute.org/pcap-31-03-exam-syllabus (opens in a new tab)
- String methods: https://docs.python.org/3.14/library/stdtypes.html#string-methods (opens in a new tab)
- Sorting HOWTO: https://docs.python.org/3.14/howto/sorting.html (opens in a new tab)
