BeginnerPython · Lesson 5 of 8

Strings & Text Processing

Indexing and slicing, string methods, f-string formatting, and cleaning messy text.

A string is a sequence of characters: name[0] is the first, name[-1] the last, and slices like name[0:3] take a range (the end is excluded). Strings are immutable — methods return new strings rather than changing the original.

Everyday methods: strip() removes surrounding spaces, lower()/upper()/title() change case, replace() substitutes text, split() breaks text into a list and "-".join(list) glues a list back together. startswith, endswith, in and count answer questions about text.

f-strings can format as they insert: {score:>5} right-aligns in 5 characters, {name:<12} left-aligns, {fee:,} adds thousands separators and {ratio:.1%} shows a percentage. These make neat tables and reports without extra libraries.

text.pyPython
name = "Amina Hassan"
print(name[0], name[-1], name[0:5], name[6:], name[::-1])   # A n Amina Hassan nassaH animA

raw = "   juma   SAID ,  form 4  "
clean_name = " ".join(raw.split(",")[0].split()).title()     # collapse spaces, fix case
print(repr(clean_name))                                       # 'Juma Said'

sentence = "Photosynthesis happens in the chloroplasts of green plants."
print(sentence.count("s"), "green" in sentence, sentence.startswith("Photo"))
print(sentence.replace("green plants", "algae").upper())

words = sentence.rstrip(".").split()
print(len(words), max(words, key=len))
print("-".join(w.lower() for w in words[:3]))                 # photosynthesis-happens-in

# Neat columns with format specifications
rows = [("Amina Hassan", 88, 0), ("Juma Said", 42, 200000), ("Neema Kimaro", 71, 50000)]
print(f"{'Name':<14}{'Score':>6}{'Balance':>12}")
for student, score, balance in rows:
    print(f"{student:<14}{score:>6}{balance:>12,}")
print(f"Pass rate: {2 / 3:.1%}")                              # Pass rate: 66.7%
Runs in your browser · Python

Key points

  • Index and slice with [start:end]; negative indexes count from the end.
  • Clean text with strip, split/join, case methods and replace.
  • Format specs in f-strings (:<14, :>6, :,, :.1%) produce tidy reports.

Exercise

Write initials(full_name) that returns 'A.H.' for 'amina hassan', and mask_phone(phone) that turns '0712345678' into '0712***678'. Then print a three-column table (name, initials, masked phone) for three students using f-string alignment.

Show solution

Try the exercise yourself first — then compare your approach with this one.

initials takes the first letter of each word, upper-cased, with dots. mask_phone keeps the first four and last three digits and replaces the middle with asterisks — slicing makes both one-liners.

text_solution.pyPython
def initials(full_name: str) -> str:
    return "".join(part[0].upper() + "." for part in full_name.split())


def mask_phone(phone: str) -> str:
    return phone[:4] + "*" * (len(phone) - 7) + phone[-3:]


students = [("amina hassan", "0712345678"), ("juma said", "0754000111"), ("neema kimaro", "0688000222")]

print(f"{'Name':<16}{'Initials':<10}{'Phone':>12}")
for name, phone in students:
    print(f"{name.title():<16}{initials(name):<10}{mask_phone(phone):>12}")
Runs in your browser · Python

Check your understanding

  1. What does "Amina"[1:3] return?

  2. Why does name.upper() not change name itself?

  3. What does f"{1234567:,}" produce?

  4. Which turns ["a", "b", "c"] into "a-b-c"?

Ask AI