Strings

Indexing, slicing, methods, f-strings, and membership.

A string is text in quotes. 'Ada' and "Ada" are the same. Triple quotes hold several lines.

Goal

Index, slice, call string methods, and build an f-string.

Index and slice

city = "Nairobi"
print(city[0], city[-1])
print(city[0:3])
print(city[:3], city[3:])
print(len(city))

Slices do not include the end index. Out-of-range index errors; out-of-range slices are empty.

Methods return new strings

raw = "  ada kwon  "
print(raw.strip())
print(raw.strip().title())
print("Nairobi".upper())
print("nairobi".startswith("nai"))
print("ada@example.com".split("@"))
print("-".join(["2024", "08", "14"]))

f-strings

name = "Ada"
score = 98
print(f"{name} scored {score}")
print(f"{name} scored {score / 100:.0%}")

Membership and replace

line = "Bring the sales CSV"
print("sales" in line)
print(line.replace("CSV", "spreadsheet"))

Several lines

note = """Line one
Line two
Line three"""
print(note)
print(note.splitlines())
Pitfall

Strings are immutable. city[0] = "n" raises TypeError. Build a new string instead.