PCAP study materials
PCAP study resources

PCAP: Strings

PCAP · Work through your exam, one topic at a time.

All guide sections

Strings

Strings

Strings are immutable sequences of Unicode code points. Candidates must know indexing, slicing (s[start:stop:step], negative indices, omitted bounds), concatenation with +, repetition with *, and membership with in. Immutability means every method returns a new string-s.upper() does not modify s.

Core methods: strip/lstrip/rstrip (whitespace or given chars), split/rsplit/splitlines, join (called on the separator, not the list), replace, find/index (the latter raises ValueError), startswith/endswith (accept tuples), upper/lower/title/capitalize/swapcase, and alignment ljust/rjust/center/zfill. Formatting: f-strings, str.format with positional/named fields and format specs ({:.2f}, {:>5}, {:,}), and %-formatting.

Traps: "a,b".split(",") versus "".split(",") (returns ['']), and " ".join([]) returning ''. Slicing never raises IndexError for out-of-range bounds, but indexing does. str.title() capitalizes after apostrophes unexpectedly. Comparisons are lexicographic by code point, so "Z" < "a". Also remember raw strings r"..." and that len counts code points, not bytes.

Worked example: "- ".join("abc".split("b")) → "a- c". split("b") yields ['a','c'], joined with "- ". Rule of thumb: sep.join(iterable) is the inverse of s.split(sep); methods never mutate.