TutreNews Learn

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

  1. Name in upper case.
  2. Price with two decimals.
  3. Output: TEA: 2.50 EUR
item = "  tea "
price = 2.5
print(f"{item.strip().upper()}: {price:.2f} EUR")

Output:

TEA: 2.50 EUR