Strings & Methods
Overview
Strings are immutable text sequences. Learn how to search, split, and format text strings.
Learning Objectives
- Use slicing parameters [start:stop:step] to extract substrings.
- Clean, replace, and split text strings.
- Combine lists of words into formatted strings efficiently.
Concept Explanation
Strings are immutable, meaning they cannot be modified in-place; editing a string creates a new string object in memory. Always use join() to concatenate lists of strings instead of iterating with += to avoid copying string content repeatedly.
Code Examples
Example 1 — Basics
This example introduces the fundamental syntax and concepts.
text = 'Python'
print(text[0:2]) # 'Py'
print(text[::-1]) # Reverses text string
Example 2 — Everyday Usage
This example demonstrates a realistic scenario handling business parameters.
# Sanitize comma separated rows
row_data = ' apples , bananas , cherries '
cleaned_items = [item.strip() for item in row_data.split(',')]
print(cleaned_items)
Example 3 — Advanced Example
This example shows clean, production-grade code structure following senior development standards.
# Build clean messages reports efficiently from log records lists
def build_report(log_records):
return '\n'.join(log_records) # Fast single-pass formatting
print(build_report(['Log: Start', 'Log: Progress', 'Log: End']))
Visual Flow
The following execution flow represents the step-by-step evaluation inside the interpreter:
Request slice index → Calculate boundaries → Copy bytes → Allocate new string object in memory
Common Mistakes
Review these common pitfalls when working with this topic:
- Trying to change string characters directly (e.g. s[0] = 'a' raises TypeError).
- Using += to concatenate strings inside loops, which leads to slow execution.
- Confusing split() parameters, causing formatting errors.
- Assuming index lookups work when substrings are missing (raises ValueError; use find() instead).
Best Practices
Enforce these Pythonic best practices in your codebase:
msg = ''
for word in words:
msg += word + ' ' # Slow loop allocations
msg = ' '.join(words) # Fast single allocation
Performance Notes
Keep these optimization guidelines in mind for performance-sensitive hotpaths:
- Because strings are immutable, concatenation using += inside loops runs in O(N^2) time complexity. Using join() runs in O(N) time complexity.
Quick Revision
Use these key summaries for last-minute revision:
- Strings are immutable Unicode sequences.
- Slice strings using [start:stop:step].
- split() breaks strings into list items.
- join() combines list strings into single lines.
- strip() cleans white spaces from ends.