Python Functions and Methods: A Topic-by-Topic Reference · Lesson 4 of 12

Lesson 4: String Methods, Part 2: Searching, Splitting and Checking

find, index, count, startswith, split, partition, splitlines, isdigit, isalpha and the other is-methods, plus ord, chr and slicing.

Lesson 4: String Methods, Part 2: Searching, Splitting and Checking

Searching

find(sub), rfind(sub), index(sub)

Position of the first (or last) match, counting from 0. find returns -1 when absent; index raises an error instead.

s = "banana"
print(s.find("an"))
print(s.rfind("an"))
print(s.find("z"))
print(s.index("n"))

Output:

1
3
-1
2

count(sub)

How many times a piece of text appears (without overlapping).

print("banana".count("a"))
print("banana".count("an"))
print("aaaa".count("aa"))

Output:

3
2
2

startswith(x), endswith(x)

Check the beginning or end. Pass a tuple to test several options.

file = "photo.JPG"
print(file.lower().endswith((".jpg", ".png")))
print("https://x.com".startswith("https"))

Output:

True
True

in

The simplest check that some text is inside another.

print("Everest" in "Mount Everest")
print("k2" in "Mount Everest")

Output:

True
False

Splitting and joining

split(sep, maxsplit)

Breaks a string into a list. With no argument it splits on any whitespace and ignores extra spaces.

print("a b   c".split())
print("2026-10-04".split("-"))
print("a,b,c,d".split(",", 2))

Output:

['a', 'b', 'c']
['2026', '10', '04']
['a', 'b', 'c,d']

rsplit(), splitlines()

rsplit splits from the right. splitlines splits at line breaks.

print("a.b.c".rsplit(".", 1))
print("one\ntwo\nthree".splitlines())

Output:

['a.b', 'c']
['one', 'two', 'three']

partition(sep), rpartition(sep)

Splits at the first (or last) separator into three parts: before, the separator, after. Handy for key=value.

print("name=Sita".partition("="))
print("a/b/c".rpartition("/"))
key, _, value = "colour=blue".partition("=")
print(key, value)

Output:

('name', '=', 'Sita')
('a/b', '/', 'c')
colour blue

Checking what a string contains

MethodTrue when the text is...
isdigit()only digits 0-9 (and at least one character)
isalpha()only letters
isalnum()only letters and digits
isspace()only whitespace
islower() / isupper()has letters and all are lower / upper case
istitle()every word starts with a capital
for text in ["123", "abc", "abc123", "  ", "Hello World", "hello"]:
    print(repr(text), text.isdigit(), text.isalpha(), text.isalnum(), text.isspace(), text.istitle())

Output:

'123' True False True False False
'abc' False True True False False
'abc123' False False True False False
'  ' False False False True False
'Hello World' False False False False True
'hello' False True True False False

Characters and codes

ord(c) and chr(n)

The number (Unicode code point) of a character, and the character of a number.

print(ord("A"), ord("a"), ord("0"))
print(chr(72), chr(105))
print(chr(ord("a") + 3))
print(ord("न"))

Output:

65 97 48
H i
d
2344

Slicing text[start:stop:step]

Take a piece of a string. Negative numbers count from the end; a step of -1 reverses.

s = "Programming"
print(s[:3])
print(s[3:])
print(s[-4:])
print(s[::2])
print(s[::-1])

Output:

Pro
gramming
ming
Pormig
gnimmargorP

sorted(text) and set(text)

A string is a sequence of characters, so you can sort it or find its distinct letters.

print(sorted("python"))
print("".join(sorted("listen")) == "".join(sorted("silent")))
print(sorted(set("mississippi")))

Output:

['h', 'n', 'o', 'p', 't', 'y']
True
['i', 'm', 'p', 's']

encode() and decode()

Convert text to bytes and back (UTF-8 is the usual encoding).

b = "नेपाल".encode("utf-8")
print(len("नेपाल"), len(b))
print(b.decode("utf-8"))

Output:

5 15
नेपाल

Try it yourself

  1. Check whether an email address has exactly one @ using count.
  2. Split "Doe, John" into first and last name and print "John Doe".
  3. Write a function that returns True if two words are anagrams (use sorted).

Next lesson: lists.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.