Learning goals
Index, slice, normalize, search, and format text without confusing mutation with replacement.
Explanation
A string is an immutable sequence of Unicode characters. Use single or double quotes for a one line literal and triple quotes for multiline text. Indexing starts at zero; -1 refers to the last character. A slice uses start:stop:step and excludes stop.
String methods return new strings rather than changing the original. strip removes leading and trailing whitespace; lower and upper change case; replace substitutes text; split creates pieces; join combines pieces. find returns -1 when the substring is absent, while an invalid individual index raises IndexError.
Example 1 Indexing and slicing
language = "Python"
print(language[0], language[-1])
print(language[1:4])
print(language[::2])
print(language[::-1])
print(len(language), "th" in language)
print("Ha" * 3)Expected output:
P n
yth
Pto
nohtyP
6 True
HaHaHaThe slice [1:4] takes indices 1, 2, and 3. The negative step reverses the sequence.
Example 2 Cleaning and formatting a record
raw_name = " aYESHA khan "
clean_name = raw_name.strip().title()
subjects = "Python, SQL, Testing"
parts = [part.strip() for part in subjects.split(",")]
score = 87.456
print(clean_name)
print(" | ".join(parts))
print(f"{clean_name}: {score:.2f}%")
print("banana".count("a"))
print("hello".replace("h", "H"))Expected output:
Ayesha Khan
Python | SQL | Testing
Ayesha Khan: 87.46%
3
HelloThe list comprehension cleans each part; Lesson 9 explains that syntax. :.2f displays two decimal places without changing score itself. title is a convenient demonstration, but real personal names do not always follow its capitalization rules.
Older formatting alternatives include "Name: {}".format(clean_name) and "Name: %s" % clean_name. Prefer f-strings for straightforward formatting in these lessons.
Common mistakes
name[0] = "A" cannot change a string. Rebuild it, for example "A" + name[1:]. strip("ab") removes a set of end characters, not necessarily the literal prefix "ab". Simple checks for @ are not complete email validation.
Student tasks
1. Normalize " PYTHON learner " to "python learner".
2. Ask for a word and report its length, first character, and reversed form. Handle an empty input without indexing it.
3. Split "red, green, blue" and join the cleaned words with " / ".
4. Format an item priced at 125.5 as "Price: 125.50".
Completion check: use at least two slices and four string methods.