Python - Strings

Overview

Estimated time: 25–35 minutes

Work with Unicode strings, slicing, common methods, and modern formatting with f-strings.

Learning Objectives

  • Create and manipulate strings; understand immutability.
  • Use slicing and common methods (lower, split, join, replace).
  • Format strings with f-strings and the format mini-language.

Prerequisites

Basics and slicing

s = "Hello, 世界"
print(len(s))        # length in code points
print(s[:5])         # 'Hello'
print(s[-2:])        # '世界'

Common methods

name = "Ada Lovelace"
print(name.lower())        # 'ada lovelace'
print(name.split())        # ['Ada', 'Lovelace']
print("-".join(["a", "b", "c"])) # 'a-b-c'
print(name.replace("Ada", "Grace"))

f-strings and formatting

pi = 3.14159265
print(f"pi rounded: {pi:.2f}")
items = [1, 2, 3]
print(f"items={items!r}")  # !r -> repr

Common Pitfalls

  • Expecting slicing to modify the string (strings are immutable).
  • Confusing bytes with str; use explicit encoding/decoding for I/O (.encode(), .decode()).

Checks for Understanding

  1. What does !r do in an f-string?
  2. How do you join a list of strings with commas?
Show answers
  1. It uses repr() representation of the value.
  2. ", ".join(list_of_strings)

Exercises

  1. Format a price with two decimals and thousands separators.
  2. Given a sentence, split into words, title-case each, and join back.