Skip to content
Kuza Ndoto Academy

Strings

Beginner → IntermediateChapter 2 · Page 9 of 565 min readUpdated 15 Nov 2026

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)
She said 'karibu' with a smile. Kuza Ndoto Hub Moi Avenue Nairobi

Escape sequences

A backslash \ gives the next character a special meaning:

SequenceMeaning
\nNew line
\tTab
\' 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")
Line one Line two It's a sunny day 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])
7 K p a

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
Kamp ala Kam apl alapmaK
city[0:4] → "Kamp" stops before index 4 index negative K a m p a l a 0123456 -7-6-5-4-3-2-1
Figure 1. Each character has a positive index (above) and a negative index (below). The slice city[0:4] takes indexes 0 to 3 and stops at the dashed line before index 4.
Common mistake

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"
TypeError: 'str' object does not support item assignment

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)
Grace Akinyi ============ True False

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"))
wanjiru kamau Wanjiru Kamau WANJIRU KAMAU m-pesa bonono 3 2 -1 True
  • strip() removes spaces (and newlines) from both ends; lstrip() and rstrip() do one side only.
  • find() returns the index of the first match, or -1 if there isn't one.
  • startswith() and endswith() return True or False.
  • Methods such as isdigit(), isalpha() and isupper() 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())
['maize', 'beans', 'rice'] maize | beans | rice ['Karibu', 'sana', 'rafiki']

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=}")
Juma bought 3 items. Total: KES 4,498.50 Pass rate: 87.5% items=3

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.

Common mistake

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; \n and other escapes add special characters.
  • Indexes start at 0, negative indexes count from the end, and slices stop before the stop index.
  • Strings are immutable: methods like upper(), strip() and replace() return new strings.
  • split() turns text into a list and join() turns a list back into text.
  • f-strings such as f"KES {amount:,.2f}" are the best way to format output.
Up next · Python BasicsInput & OutputRead what the user types and print results.
→

Tip: use the ← and → keys to move between pages.