Strings
String methods and functions
Choose the right string method for a task.
Python has many ready-made string methods. A method is called with a dot: s.upper(). Because strings are immutable, methods return new strings; the original is never changed.
- len(s): the length.
- title(), lower(), upper(): the string in title case (first letter of each word capital), small letters, or capitals. 'good morning'.title() is 'Good Morning'.
- count(str, start, end): how many times str occurs. 'banana'.count('n') is 2.
- find(str, start, end): the index where str first occurs, or -1 if it is not there. 'mango'.find('g') is 3.
- index(): like find(), but raises a ValueError if not found.
- startswith() and endswith(): True or False.
Methods that test a string and return True or False: isalnum() (only letters and digits), islower(), isupper(), isspace() (only spaces), istitle() (in title case).
Methods that change the shape of a string:
- lstrip(), rstrip(), strip(): remove spaces from the left, the right, or both ends.
- replace(old, new): replace every occurrence of old with new.
- sep.join(str): put sep between the characters: '-'.join('abc') is 'a-b-c'.
- partition(sep): split at the first sep into a tuple of three parts (before, sep, after): '2026-10-24'.partition('-') gives ('2026', '-', '10-24').
- split(sep): split into a list of pieces; with no sep, it splits at spaces: 'red green blue'.split() gives ['red', 'green', 'blue'].
Methods return new strings; the original never changes.
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.