Change case, trim, split, join, search, replace and count, all with methods that return new strings.
# upper and lower
"hello".upper()
# ans: "HELLO"
"HELLO".lower()
# ans: "hello"
"hello world".title()
# ans: "Hello World"
"hello".capitalize()
# ans: "Hello"
# remove whitespace
" hello ".strip()
# ans: "hello"
" hello ".lstrip()
# ans: "hello "
" hello ".rstrip()
# ans: " hello"
l = left end only, r = right end only.
# split a string into a list
"apple,banana,cherry".split(",")
# ans: ['apple', 'banana', 'cherry']
"one two three".split()
# ans: ['one', 'two', 'three']
With no argument, split() splits on any run of whitespace.
# join a list into a string
",".join(["a", "b", "c"])
# ans: "a,b,c"
" ".join(["Hello", "World"])
# ans: "Hello World"
The string you call join on is the glue between the items.
# find a substring
"hello world".find("world")
# ans: 6
"hello world".find("xyz")
# ans: -1
"hello world".index("world")
# ans: 6
Both return the index where the match starts.
# replace a substring
"hello world".replace("world", "Python")
# ans: "hello Python"
"aaa".replace("a", "b", 2)
# ans: "bba" (replaces the first 2)
# check the start and end
"hello".startswith("he")
# ans: True
"hello".endswith("lo")
# ans: True
# count occurrences
"hello".count("l")
# ans: 2
"banana".count("a")
# ans: 3
Predict each result, then press → to check.
# case methods?
"HeLLo".lower()
# ans: "hello"
"hello".upper()
# ans: "HELLO"
# strip only the ends?
" hello ".strip()
# ans: "hello"
# split with a limit?
"a-b-c-d".split("-", 2)
# ans: ['a', 'b', 'c-d']
Only the first 2 separators are used; the rest stays in the last piece.
# join with numbers?
"-".join([1, 2, 3])
# ans: TypeError (join needs strings)
"-".join(["1", "2", "3"])
# ans: "1-2-3"
# find vs index?
"hello".find("x")
# ans: -1
"hello".index("x")
# ans: ValueError
# replace all?
"aaa".replace("a", "b")
# ans: "bbb"
# case sensitive?
"Hello".startswith("h")
# ans: False
"Hello".startswith("H")
# ans: True
# count overlapping?
"aaa".count("aa")
# ans: 1 (non-overlapping)
After matching aa at 0, the search continues from index 2, where only one a is left.
# empty split?
"".split()
# ans: []
" ".split()
# ans: []
# join an empty list?
",".join([])
# ans: ""
Methods never change the original string; keep the result.
find, count, startswith and friends compare exactly.
-1 or a ValueError when the text isn't there.
join only accepts strings.