Python Strings · Lesson 23 of 149

Python Searching, Splitting and Joining Strings

What you will learn

  • Finding text: find, rfind, index, count
  • Breaking a string apart: split, rsplit, splitlines, partition
  • Putting pieces together: join
  • Removing a prefix or suffix: removeprefix, removesuffix
  • Replacing characters in bulk: translate

1. Finding text

find(text) returns the index where the text first appears, or -1 if it is not there:

s = "hello world"
print(s.find("o"), s.rfind("o"), s.find("z"))
print("hello".find("l", 3))
4 7 -1
3
  • find searches from the left; rfind searches from the right.
  • A second number says where to start: "hello".find("l", 3) starts at index 3.
  • A third number says where to stop (the stop index is excluded): "hello".find("lo", 1, 4) is -1, but with 5 as the stop it is 3.

index works like find, but raises an error when the text is missing:

print("hello".index("l"), "hello".rindex("l"))
"hello".index("z")
2 3
ValueError: substring not found

Choose find when "not found" is a normal case that you test for, and index when it should never happen. If you only need yes or no, use in (lesson 4.1).

Counting

count says how many times a text appears. It counts without overlapping:

print("banana".count("a"), "banana".count("an"))
print("aaaa".count("aa"))
3 2
2

"aaaa".count("aa") is 2, not 3: after one match, the search continues after it.

Quick check: what does `"hello".find("x")` return?

-1, which means "not found". It does not raise an error.

2. Splitting

split(sep) cuts a string at each separator and returns a list of the pieces (lists are covered in chapter 7):

print("a,b,c".split(","))
print("a,b,,c".split(","))
print("a,b,c,".split(","))
['a', 'b', 'c']
['a', 'b', '', 'c']
['a', 'b', 'c', '']

Notice that two commas in a row give an empty string in between, and a comma at the end gives an empty string at the end.

Splitting on white space

With no separator, split() splits on any amount of white space (spaces, tabs, new lines) and ignores the ends:

print("a b  c".split())
print("a b  c".split(" "))
print(" a b ".split())
print("a\tb  c\nd".split())
['a', 'b', 'c']
['a', 'b', '', 'c']
['a', 'b']
['a', 'b', 'c', 'd']

split() is the right way to get the words of a sentence. split(" ") with one space keeps the empty pieces.

Limits and the right side

A second number limits the number of cuts. rsplit cuts from the right:

print("a,b,c".split(",", 1))
print("a,b,c".rsplit(",", 1))
print("path/to/file.txt".rsplit("/", 1))
['a', 'b,c']
['a,b', 'c']
['path/to', 'file.txt']

An empty separator is an error: "abc".split("") raises ValueError: empty separator. To get single characters, use list("abc").

Splitting lines

splitlines() splits at line breaks (\n, \r\n and others), and does not leave an empty piece after a final line break:

print("l1\nl2\r\nl3".splitlines())
print("l1\nl2\n".splitlines())
print("l1\nl2\n".split("\n"))
['l1', 'l2', 'l3']
['l1', 'l2']
['l1', 'l2', '']

Splitting in exactly two: partition

partition(sep) splits at the first separator into exactly three parts: before, the separator, after. If the separator is missing, you get the whole string and two empty strings:

print("k=v=w".partition("="))
print("k=v=w".rpartition("="))
print("kv".partition("="))
('k', '=', 'v=w')
('k=v', '=', 'w')
('kv', '', '')

rpartition splits at the last separator. Because the result always has three parts, it is convenient to unpack into names:

line = "  key :  value  "
k, _, v = line.partition(":")
print(repr(k.strip()), repr(v.strip()))
'key' 'value'

(The underscore _ is a common name for a part you do not need.)

3. Joining

join is the opposite of split. The separator goes first, then the pieces in brackets:

print(",".join(["a", "b", "c"]))
print(" ".join(["rice", "salt", "oil"]))
print("".join(["a", "b"]))
print(repr("-".join([])))
a,b,c
rice salt oil
ab
''

Joining an empty list gives the empty string. It may feel backwards at first: join is a method of the separator, not of the list.

The pieces must be strings. Numbers need converting first:

",".join([1, 2])
TypeError: sequence item 0: expected str instance, int found
nums = [1, 2, 3]
print(",".join(str(n) for n in nums))
print(",".join(map(str, nums)))
1,2,3
1,2,3

(The first form is a generator expression, chapter 12; map applies a function to every item.)

join is also the right tool for building long strings from many pieces. Lesson 4.7 explains why.

4. Removing a prefix or suffix

removeprefix and removesuffix cut off text only when it is really there (they need Python 3.9 or later):

print("prefix_name".removeprefix("prefix_"))
print("file.txt".removesuffix(".txt"))
print("abc".removeprefix("x"))
name
file
abc

This is safer than strip("prefix_"), which removes characters, not a whole text.

5. Translating characters

translate replaces or deletes single characters in one pass. Build the table with str.maketrans:

table = str.maketrans("abc", "xyz")
print("aabbcc".translate(table))
print("hello".translate(str.maketrans("", "", "l")))
xxyyzz
heo
  • maketrans("abc", "xyz") maps a to x, b to y, c to z.
  • A third argument lists characters to delete.

Worked example: tidy a sentence and a file name

Count the words of a sentence, and turn each word into Title Case. Then pull the extension out of a file name.

sentence = "the quick brown fox"
words = sentence.split()
print(len(words))
print(" ".join(w.capitalize() for w in words))
print(" ".join(reversed(words)))

name = "file.tar.gz"
print(name.rsplit(".", 1))
print(name.rpartition(".")[2])
4
The Quick Brown Fox
fox brown quick the
['file.tar', 'gz']
gz
Step What it does
split() breaks the sentence into 4 words
capitalize() on each, then join rebuilds it with capitals
reversed(words) then join the words in reverse order
rsplit(".", 1) cuts only at the last dot
rpartition(".")[2] the part after the last dot

The sentence and the file name are made up for the example.

Common mistakes

  • Using find result as a truth value. "abc".find("a") is 0, which counts as false, and -1, for "not found", counts as true. Test != -1, or use in.
  • Using split(" ") for words. Repeated spaces give empty pieces; use split().
  • Forgetting that join belongs to the separator. Write ",".join(items), not items.join(",").
  • Joining numbers. Convert with str(...) first.
  • Using strip to remove a prefix or suffix. It removes characters, not a text; use removeprefix or removesuffix.

Key takeaways

  • find gives an index or -1; index raises ValueError instead; count counts without overlap.
  • split() (no separator) gives the words; split(sep) keeps empty pieces; rsplit and a limit control where it cuts.
  • splitlines() splits at line breaks; partition always gives three parts.
  • sep.join(pieces) is the opposite of split, and every piece must be a string.
  • removeprefix, removesuffix and translate remove or replace exact text or single characters.

Practice

1. What are "hello world".find("o") and "hello world".rfind("o")?

Show answer

4 and 7: the first and the last o.

2. What does "a b c".split() give, and what does "a b c".split(" ") give?

Show answer

['a', 'b', 'c'] and ['a', 'b', '', 'c']. The one-space version keeps an empty piece.

3. Join ["2026", "10", "20"] into "2026-10-20".

Show answer

"-".join(["2026", "10", "20"]).

4. Get the user name from "rina@example.com" using partition.

Show answer

"rina@example.com".partition("@")[0] gives rina. Or user, _, domain = email.partition("@").

5. Join the list [3, 4, 5] into the text "3 4 5".

Show answer

" ".join(str(n) for n in [3, 4, 5]) or " ".join(map(str, [3, 4, 5])).

6. What is the file extension of "photo.final.png", using rpartition?

Show answer

"photo.final.png".rpartition(".")[2] gives png.