String Methods
In the last lesson you learned to build strings and pick out parts of them. Python also gives every string a set of built-in tools for changing case, cleaning up spaces, finding and replacing text, and more. These tools are called methods.
What is a method?
A method is a function that belongs to a value. You call it by writing a dot after the value, then the method name and parentheses:
text = "hello" print(text.upper())
Read text.upper() as "the upper-case version of text".
String methods never change the original string. They give you back a new string, which you can print or store in a variable:
text = "hello" shout = text.upper() print(shout) print(text) # still lower case
Changing case
text = "learn Python today" print(text.upper()) print(text.lower()) print(text.title()) print(text.capitalize())
lower() is especially useful for comparing text that people type, because "Yes", "YES" and "yes" all become "yes".
Cleaning up spaces with strip()
strip() removes spaces from both ends of a string, but not from the middle. It's very useful for cleaning up what people type:
messy = " hello there "
print("[" + messy + "]")
print("[" + messy.strip() + "]")The square brackets are just there so you can see where the spaces start and end.
Going deeper: lstrip() and rstrip() optional
lstrip() removes spaces from the left end only, and rstrip() from the right end only. strip() also removes new lines and tabs, which is handy when reading lines from a file later on.
messy = " hello there "
print("[" + messy.lstrip() + "]")
print("[" + messy.rstrip() + "]")Chaining methods
Because each method gives back a new string, you can call another method straight away. Python works from left to right:
name = " ADA lovelace " print(name.strip().title())
First strip() removes the spaces, then title() capitalises each word.
Finding and replacing
sentence = "I like cats. Cats are great."
print(sentence.replace("cats", "dogs"))
print(sentence.count("a"))
print(sentence.startswith("I"))
print(sentence.endswith("!"))Notice that replace("cats", "dogs") didn't change Cats with a capital C. Methods are case-sensitive.
find() tells you the index where some text starts, or -1 if it isn't there:
sentence = "I like cats. Cats are great."
print(sentence.find("are"))
print(sentence.find("birds"))Checking for text with in
The in operator asks "does this text appear inside that text?" and answers True or False:
email = "[email protected]" print("@" in email) print("gmail" in email)
You'll use True and False answers like this a lot once you learn if statements.
Splitting and joining
split() breaks a string into pieces. It gives you a list, a collection of values in square brackets. Lists get a whole lesson in Part 2; for now, just know that you can pick items from a list by index, exactly like characters in a string:
sentence = "the quick brown fox" words = sentence.split() print(words) print(words[0]) print(words[-1])
With no argument, split() splits on spaces. Give it a character to split somewhere else:
csv_line = "apple,banana,cherry"
print(csv_line.split(","))join() does the opposite: it glues pieces back together with a separator in between:
words = ["the", "quick", "brown", "fox"]
print("-".join(words))
print(" ".join(words))Methods inside f-strings
You can call methods inside the braces of an f-string:
name = "ada"
print(f"Hello, {name.title()}! Your name has {len(name)} letters.")Exercises
Exercise 1: Clean up a username
Users often type extra spaces and random capitals. Clean up the username so it prints ada_lovelace.
username = " Ada_LoveLace "
strip() removes the spaces at both ends.
You can chain methods: username.strip().lower().
Exercise 2: Fix the typo
The word Pyton is misspelled twice. Use a method to print the sentence with both fixed: I love Python. Python is fun!
sentence = "I love Pyton. Pyton is fun!"
There's a method that swaps one piece of text for another everywhere it appears.
sentence.replace("Pyton", "Python") gives the fixed sentence.
Exercise 3: Make it loud
Remove the extra spaces, turn the message into capitals and add an exclamation mark, so it prints HELLO WORLD!
message = " hello world "
Chain two methods: one removes the spaces, the other makes capitals.
message.strip().upper() gives HELLO WORLD. Then join "!" on the end with +.
Exercise 4: Email parts
Split the email address into the username and the domain, and print them as Username: ada and Domain: example.com.
email = "[email protected]"
email.split("@") gives a list with two parts.
The username is parts[0] and the domain is parts[1].
String methods at a glance
A quick reference for later, including some useful methods this lesson didn't cover. Remember: every method gives back a new value and leaves the original string unchanged. Results are shown with quotes, so you can see exactly where each string starts and ends.
Changing case
| Method | What it does | Example | Result |
|---|---|---|---|
upper() |
All capitals | "Hello".upper() |
'HELLO' |
lower() |
All lower case | "Hello".lower() |
'hello' |
title() |
Capital at the start of each word | "ada lovelace".title() |
'Ada Lovelace' |
capitalize() |
Capital first letter, the rest lower case | "hELLO there".capitalize() |
'Hello there' |
swapcase() |
Swaps capitals and lower case | "Hello".swapcase() |
'hELLO' |
Cleaning up and replacing
| Method | What it does | Example | Result |
|---|---|---|---|
strip() |
Removes spaces (and new lines) from both ends | " hi ".strip() |
'hi' |
lstrip(), rstrip() |
Removes them from the left or right end only | " hi ".rstrip() |
' hi' |
strip(chars) |
Removes the given characters from both ends | "--hi--".strip("-") |
'hi' |
replace(old, new) |
Swaps every old for new |
"a-b-c".replace("-", "+") |
'a+b+c' |
removeprefix(text) |
Removes text from the start, if it's there |
"Mr Smith".removeprefix("Mr ") |
'Smith' |
removesuffix(text) |
Removes text from the end, if it's there |
"photo.jpg".removesuffix(".jpg") |
'photo' |
Finding and counting
| Method | What it does | Example | Result |
|---|---|---|---|
find(text) |
Position of the first match, or -1 if not found |
"banana".find("an") |
1 |
rfind(text) |
Position of the last match, or -1 |
"banana".rfind("an") |
3 |
index(text) |
Like find(), but raises ValueError if not found |
"banana".index("n") |
2 |
count(text) |
How many times text appears |
"banana".count("a") |
3 |
startswith(text) |
Does the string start with text? |
"photo.jpg".startswith("ph") |
True |
endswith(text) |
Does the string end with text? |
"photo.jpg".endswith(".png") |
False |
Checking what's inside
| Method | What it does | Example | Result |
|---|---|---|---|
isdigit() |
Only digits? Great for checking typed numbers | "2024".isdigit() |
True |
isalpha() |
Only letters? | "abc1".isalpha() |
False |
isalnum() |
Only letters and digits? | "abc1".isalnum() |
True |
isspace() |
Only spaces, tabs or new lines? | " ".isspace() |
True |
isupper(), islower() |
All capitals, or all lower case? | "HELLO".isupper() |
True |
Splitting and joining
| Method | What it does | Example | Result |
|---|---|---|---|
split() |
Splits on spaces into a list of words | "a b c".split() |
['a', 'b', 'c'] |
split(sep) |
Splits on sep |
"a,b,c".split(",") |
['a', 'b', 'c'] |
split(sep, n) |
Splits at most n times |
"a,b,c".split(",", 1) |
['a', 'b,c'] |
splitlines() |
Splits into lines | "one\ntwo".splitlines() |
['one', 'two'] |
partition(sep) |
Splits at the first sep into three parts |
"key=value".partition("=") |
('key', '=', 'value') |
sep.join(items) |
Glues items together with sep between them |
"-".join(["a", "b", "c"]) |
'a-b-c' |
Lining up text
| Method | What it does | Example | Result |
|---|---|---|---|
center(width) |
Centres the text in width characters |
"hi".center(6) |
' hi ' |
ljust(width) |
Pads on the right to width characters |
"hi".ljust(5) |
'hi ' |
rjust(width) |
Pads on the left to width characters |
"hi".rjust(5) |
' hi' |
zfill(width) |
Pads a number with zeros on the left | "42".zfill(5) |
'00042' |
Summary
- A method is a function that belongs to a value:
text.upper(). - String methods give back a new string. The original never changes.
upper(),lower()andtitle()change case.strip()removes spaces from the ends.replace()swaps text,count()counts it, andfind()gives its position (or-1)."x" in textchecks whether some text appears in a string.split()breaks a string into a list of pieces, and"-".join(pieces)glues them back together.