Python String Methods
Strings come with dozens of built-in methods — functions you call with a dot, like text.upper(). Because strings are immutable, every method returns a new string (or another value) and leaves the original untouched.
title = "python basics"
print(title.upper())
print(title) # unchangedPYTHON BASICS
python basics
Changing case
| Method | Effect | "hello World" becomes |
|---|---|---|
upper() |
all uppercase | HELLO WORLD |
lower() |
all lowercase | hello world |
title() |
first letter of each word uppercase | Hello World |
capitalize() |
first letter of the string uppercase | Hello world |
swapcase() |
swap upper and lower | HELLO wORLD |
casefold() |
aggressive lowercase for comparisons | hello world |
Removing whitespace
Text from users and files often has stray spaces or newlines at the ends. The strip family removes them:
raw = " apple pie \n"
print("[" + raw.strip() + "]")
print("[" + raw.lstrip() + "]")
print("[" + raw.rstrip() + "]")
print("--==hello==--".strip("-=")) # strip specific characters[apple pie]
[apple pie
]
[ apple pie]
hello
Searching
sentence = "the cat sat on the mat"
print(sentence.find("at")) # index of first match
print(sentence.rfind("at")) # index of last match
print(sentence.find("dog")) # -1 when not found
print(sentence.count("the"))
print(sentence.startswith("the"))
print(sentence.endswith(("mat", "rug"))) # a tuple means "any of these"5
20
-1
2
True
True
index() works like find() but raises ValueError instead of returning -1 when nothing is found.
Replacing
replace(old, new) swaps every occurrence; an optional third argument limits how many:
s = "one fish two fish red fish"
print(s.replace("fish", "bird"))
print(s.replace("fish", "bird", 1))one bird two bird red bird
one bird two fish red fish
Splitting and joining
These two are the most useful methods of all. split() breaks a string into a list; join() glues a list of strings back together using the string it's called on as the glue:
csv_line = "Hanoi,Hue,Da Nang,Saigon"
cities = csv_line.split(",")
print(cities)
print(" -> ".join(cities))
print("a b c".split()) # no argument: split on any whitespace
print("2025-06-01".split("-", 1)) # at most one split
lines = "first\nsecond\nthird".splitlines()
print(lines)['Hanoi', 'Hue', 'Da Nang', 'Saigon']
Hanoi -> Hue -> Da Nang -> Saigon
['a', 'b', 'c']
['2025', '06-01']
['first', 'second', 'third']
Testing the contents
Methods starting with is return True or False:
| Method | True when every character is… |
|---|---|
isdigit() |
a digit ("2025") |
isalpha() |
a letter ("abc") |
isalnum() |
a letter or digit ("abc123") |
isspace() |
whitespace |
isupper() / islower() |
upper / lower case (cased letters only) |
for value in ["123", "12.5", "abc", "abc123", ""]:
print(repr(value), value.isdigit(), value.isalpha(), value.isalnum())'123' True False True
'12.5' False False False
'abc' False True True
'abc123' False False True
'' False False False
Notice that an empty string returns False for all of them, and "12.5" is not all digits because of the dot.
Alignment and padding
print("|" + "left".ljust(10) + "|")
print("|" + "right".rjust(10) + "|")
print("|" + "mid".center(10, "*") + "|")
print("42".zfill(5))|left |
| right|
|***mid****|
00042
Chaining methods
Because each method returns a new string, you can call another method on the result:
messy = " HeLLo, PyThOn! "
clean = messy.strip().lower().replace("!", "")
print(clean)hello, python
Tip: To see every string method, run
print(dir(str))in a playground, orhelp(str.split)for details on one of them.
Test yourself
What does "a,b,c".split(",") return?
- "abc"
- ["a", "b", "c"]
- ("a", "b", "c")
- ["a,b,c"]
What does "-".join(["x", "y", "z"]) return?
- "x-y-z"
- "-x-y-z-"
- "xyz"
- ["x-", "y-", "z"]
What does "hello".find("z") return?
- None
- 0
- -1
- It raises ValueError