Python String Methods
What you will learn
- That string methods return new strings and never change the original
- Changing case:
upper,lower,title,capitalize,casefold - Removing unwanted characters with
stripand changing text withreplace - Testing the start and end:
startswith,endswith - The is-tests:
isdigit,isalpha,isalnum,isspaceand more - Padding with
zfill,ljust,rjust,center, and chaining
1. What a method is
A method is a function that belongs to a value. You call it with a dot: value.method(...). Strings have dozens of methods. This lesson covers the ones you will use most; the next lesson covers searching, splitting and joining.
The most important fact: strings are immutable (lesson 2.6), so a method returns a new string and leaves the original alone.
t = "hello"
t.upper()
print(t)
t = t.upper()
print(t)
hello
HELLO
The line t.upper() made "HELLO" and threw it away. To keep the result, store it: t = t.upper().
To see every method of a string, type help(str) in the shell (lesson 1.4).
Quick check: after `name = "rina"` and `name.upper()`, what is `name`?
Still "rina". The method returned a new string, and nothing stored it.
2. Changing case
s = "hello wORLD, it's pYthon"
print(s.upper())
print(s.lower())
print(s.capitalize())
print(s.swapcase())
HELLO WORLD, IT'S PYTHON
hello world, it's python
Hello world, it's python
HELLO World, IT'S PyTHON
| Method | What it does |
|---|---|
upper() |
all capitals |
lower() |
all lower case |
capitalize() |
first letter capital, the rest lower case |
swapcase() |
swaps the case of every letter |
title() |
capital at the start of each word (see the trap below) |
casefold() |
an aggressive lower(), for comparing text |
Comparing ignoring case
Change both sides to the same case:
print("Python".lower() == "PYTHON".lower())
True
For text in other languages, use casefold(), which handles special letters such as the German ß:
print("Straße".lower() == "STRASSE".lower())
print("Straße".casefold() == "STRASSE".casefold())
False
True
The title() trap
title() treats an apostrophe as the start of a new word, and a letter after a digit as well:
print("they're bill's".title())
print("1st place".title())
They'Re Bill'S
1St Place
For ordinary words, the standard library's string.capwords is safer:
import string
print(string.capwords("they're bill's son"))
They're Bill's Son
(capwords also squeezes repeated spaces into one.)
3. Removing characters: strip
strip() removes white space (spaces, tabs, new lines) from both ends. lstrip() strips the left and rstrip() the right:
print(repr(" hi ".strip()))
print(repr(" hi ".lstrip()))
print(repr(" hi ".rstrip()))
print(repr("\t\n hi \n".strip()))
'hi'
'hi '
' hi'
'hi'
Give it a string of characters to remove those instead. It removes any of them from the ends, in any order, and stops at the first other character:
print("xxhixx".strip("x"))
print("--a--".lstrip("-"))
print("abcba".strip("ab"))
hi
a--
c
strip never touches the middle: "a b".strip() stays "a b".
4. Changing text: replace
replace(old, new) swaps every occurrence. A third number limits how many:
print("a-b-c".replace("-", "+"))
print("aaa".replace("a", "b", 2))
print("hello".replace("l", ""))
a+b+c
bba
heo
Replacing with "" deletes the text. replace is case-sensitive and works on exact text, not patterns (patterns need the re module, lesson 17.6).
5. Starts and ends
startswith and endswith give True or False. Give a tuple of options to test several at once:
print("Pathkori".startswith("Path"), "Pathkori".endswith("kori"))
print("Pathkori".startswith(("A", "P")))
print("file.txt".endswith((".txt", ".md")))
True True
True
True
6. The is-tests
These methods answer a yes-or-no question about the whole string:
| Method | True when the string... |
|---|---|
isdigit() / isdecimal() |
is only digits ("42", not "4.2" or "-5") |
isalpha() |
is only letters |
isalnum() |
is only letters and digits |
isspace() |
is only white space |
isupper() / islower() |
has letters that are all upper or all lower case |
istitle() |
looks like a title: "Hello World" |
isidentifier() |
could be a Python name |
print("42".isdigit(), "4.2".isdigit(), "-5".isdigit())
print("abc".isalpha(), "abc1".isalpha(), "abc1".isalnum())
print(" ".isspace(), "".isspace())
print("ABC".isupper(), "abc".islower(), "Hello World".istitle())
True False False
True False True
True False
True True True
- The empty string is
Falsefor all of these:"".isalpha()and"".isdigit()areFalse. "4.2"and"-5"are not "only digits", because of the point and the minus sign. To test for a number with decimals or a sign, try converting it (lesson 2.4).- For plain digits
0to9,isdecimal()andisdigit()agree. They differ for exotic characters such as"²", andisnumeric()also accepts"½".
7. Padding and aligning
These make text a fixed width, useful for tidy columns and numbers:
print("cat".center(9, "*"))
print("cat".ljust(6, ".") + "|")
print("cat".rjust(6) + "|")
print("7".zfill(3), "-7".zfill(4))
***cat***
cat...|
cat|
007 -007
| Method | What it does |
|---|---|
center(width, fill) |
centres the text |
ljust(width, fill) |
pads on the right (left-aligned) |
rjust(width, fill) |
pads on the left (right-aligned) |
zfill(width) |
pads with zeros on the left, keeping a sign |
Without a fill character, the padding is spaces. If the text is already as wide as width or wider, it is left unchanged. Lesson 4.6 shows a more flexible way to align, with formatting.
8. Chaining methods
Every method returns a string, so you can call the next method on the result. They run left to right:
raw = " rINA hOQUE "
clean = raw.strip().title()
print(clean)
Rina Hoque
Here strip() removed the spaces and then title() capitalised each word.
Worked example: clean up a username
Users type their username in all sorts of ways. Make it tidy for comparing: no spaces at the ends, all lower case, and spaces inside replaced by underscores.
typed = " Rina Hoque "
username = typed.strip().lower().replace(" ", "_")
print(username)
print(username.isalpha(), username.replace("_", "").isalpha())
rina_hoque
False True
| Step | Result |
|---|---|
strip() |
"Rina Hoque" |
lower() |
"rina hoque" |
replace(" ", "_") |
"rina_hoque" |
The first test is False because of the underscore. After removing it, the remaining characters are all letters, so the second is True. The name is made up.
Common mistakes
- Calling a method and not storing the result.
s.upper()alone changes nothing. - Expecting
strip()to remove spaces in the middle. - Using
title()on text with apostrophes. Usestring.capwords. - Using
isdigit()to test for a negative or decimal number. - Forgetting the brackets.
s.upperis the method itself;s.upper()calls it.
Key takeaways
- String methods return new strings; store the result if you need it.
lower()andcasefold()help compare text;title()has traps.strip()trims the ends,replace(old, new)swaps text.startswithandendswithaccept a tuple of options.- The is-tests (
isdigit,isalpha, ...) areFalsefor an empty string. zfill,ljust,rjustandcenterpad text to a width; methods can be chained left to right.
Practice
1. What do "Python".upper() and "Python".lower() give? Does "Python" change?
Show answer
"PYTHON" and "python". The original stays "Python", because methods return new strings.
2. Clean " hello world " so it has no outer spaces and each word starts with a capital.
Show answer
" hello world ".strip().title() gives Hello World.
3. What does "banana".replace("a", "o", 2) give?
Show answer
"bonona". Only the first two a characters are replaced.
4. Write a test that is True when a file name ends in .png or .jpg.
Show answer
name.endswith((".png", ".jpg")).
5. What do "123".isdigit(), "12.3".isdigit() and "".isdigit() give?
Show answer
True, False and False.
6. Show the number 5 as 005 and the text "id" right-aligned in a width of 6.
Show answer
"5".zfill(3) gives 005, and "id".rjust(6) gives id.