Lists, dictionaries, strings
Working with strings
Goal: Slice, search and format text · 9 min
Strings behave like sequences of characters: s[0], s[-1], len(s), slicing s[2:5], s[::-1] (reversed). Unlike lists they are immutable — methods return new strings.
Common methods: .upper(), .lower(), .strip() (remove surrounding spaces), .replace(a, b), .split(), "-".join(list), .startswith(), .count(), .find().
f-strings insert values: f"{name} is {age} years old"; format numbers with {price:.2f} (two decimals).
Worked example: Formatting a receipt line
- Name in upper case.
- Price with two decimals.
- Output:
TEA: 2.50 EUR
item = " tea "
price = 2.5
print(f"{item.strip().upper()}: {price:.2f} EUR")Output:
TEA: 2.50 EUR