Strings
A string is a piece of text: a name, a message, a phone number, even a whole book. Strings are one of the most used types in Python, and Python gives you powerful tools to slice, search, change and format them.
Creating strings
Put text inside single quotes or double quotes. Both work the same; choose the one that avoids clashing with quotes inside your text. Triple quotes let a string span several lines.
city = "Kampala" greeting = 'Habari yako?' quote = "She said 'karibu' with a smile." address = """Kuza Ndoto Hub Moi Avenue Nairobi""" print(quote) print(address)
Escape sequences
A backslash \ gives the next character a special meaning:
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\' and \" | A quote that doesn't end the string |
\\ | A real backslash |
print("Line one\nLine two")
print('It\'s a sunny day')
print("C:\\Users\\Aisha")
Putting r before a string makes it a raw string, where backslashes are kept as they are: r"C:\Users\Aisha" prints the same path. Raw strings are common in file paths and regular expressions.
Length, indexing and slicing
len() counts the characters in a string. Each character also has a position number called an index. Indexes start at 0, and negative indexes count from the end.
K a m p a l a 0 1 2 3 4 5 6 -7 -6 -5 -4 -3 -2 -1
city = "Kampala" print(len(city)) print(city[0]) print(city[3]) print(city[-1])
A slice [start:stop] takes a section of the string. It includes start but stops before stop. Leave out start to begin at the start, or stop to go to the end. An optional third number is the step.
city = "Kampala" print(city[0:4]) # positions 0, 1, 2, 3 print(city[4:]) # from position 4 to the end print(city[:3]) # the first three characters print(city[1:6:2]) # positions 1, 3, 5 print(city[::-1]) # step backwards: reversed
city[0:4] takes indexes 0 to 3 and stops at the dashed line before index 4.Indexing past the end, such as city[7] on a 7-character string, raises IndexError: string index out of range. The last valid index is always len(city) - 1, or simply -1. Slices are more forgiving: city[4:100] just returns "ala".
Strings can't be changed
Strings are immutable: once created, their characters can't be changed in place. Trying to assign to an index fails:
city = "Kampala" city[0] = "k"
Instead, build a new string and assign it to the variable: city = "k" + city[1:] gives "kampala".
Joining and repeating
+ joins (concatenates) strings and * repeats them. The in keyword checks whether one string appears inside another.
first = "Grace"
last = "Akinyi"
full = first + " " + last
print(full)
print("=" * 12)
print("Aki" in full)
print("aki" in full)
The last check is False because comparisons are case-sensitive: lowercase "a" is not the same character as uppercase "A".
Useful string methods
A method is a function that belongs to a value. You call it with a dot: text.upper(). String methods never change the original string; they return a new one.
name = " wanjiru kamau "
clean = name.strip()
print(clean)
print(clean.title())
print(clean.upper())
print("M-PESA".lower())
print("banana".replace("a", "o"))
print("banana".count("a"))
print("banana".find("n"))
print("banana".find("z"))
print("0712345678".startswith("07"))
strip()removes spaces (and newlines) from both ends;lstrip()andrstrip()do one side only.find()returns the index of the first match, or-1if there isn't one.startswith()andendswith()returnTrueorFalse.- Methods such as
isdigit(),isalpha()andisupper()test what a string contains.
Splitting and joining
split() breaks a string into a list of smaller strings (a list is an ordered collection in square brackets; see Lists). join() does the reverse.
crops = "maize,beans,rice"
parts = crops.split(",")
print(parts)
print(" | ".join(parts))
print("Karibu sana rafiki".split())
With no argument, split() splits on any whitespace.
Formatting with f-strings
An f-string starts with f before the quote. Inside it, anything in curly braces {} is worked out and inserted into the text. It's the clearest way to build messages from variables.
name = "Juma"
items = 3
price = 1499.5
score = 0.875
print(f"{name} bought {items} items.")
print(f"Total: KES {items * price:,.2f}")
print(f"Pass rate: {score:.1%}")
print(f"{items=}")
After a colon inside the braces you can add a format specifier: .2f means two decimal places, , adds thousands separators and .1% shows a percentage with one decimal place. Writing {items=} prints both the name and the value, which is handy for debugging.
Forgetting the f. print("Hello {name}") prints the braces literally as Hello {name}. You need print(f"Hello {name}").
Key points
- Strings use single, double or triple quotes;
\nand other escapes add special characters. - Indexes start at 0, negative indexes count from the end, and slices stop before the
stopindex. - Strings are immutable: methods like
upper(),strip()andreplace()return new strings. split()turns text into a list andjoin()turns a list back into text.- f-strings such as
f"KES {amount:,.2f}"are the best way to format output.
Tip: use the ← and → keys to move between pages.
