Python's str type provides dozens of built-in methods for text manipulation, all of which return new strings (since strings are immutable). The most commonly used include: .upper(), .lower(), .title(), .capitalize() (case transformations); .strip(), .lstrip(), .rstrip() (whitespace removal); .split(), .rsplit() (split into a list); .join(iterable) (join a list into a string); .replace(old, new) (substitution); and .find(), .index(), .count() (searching).
Testing methods return booleans: .startswith(), .endswith(), .isdigit(), .isalpha(), .isalnum(), .isspace(), .isupper(), .islower(). Alignment methods pad strings: .center(width), .ljust(width), .rjust(width), .zfill(width). .encode(encoding) converts a string to bytes (default UTF-8), and bytes.decode(encoding) goes the other way.
The most important string method to master is .join(), which is Python's idiomatic way to concatenate a sequence of strings: ', '.join(['a', 'b', 'c']) produces 'a, b, c'. Using .join() instead of + in a loop is critical for performance: repeated + concatenation creates a new string object each time (O(n²)), while .join() allocates once (O(n)). String methods, combined with f-strings and the re module, give Python comprehensive text-processing capabilities.
Discussed in:
- Chapter 7: Strings and Text Processing — Common String Methods