Python Strings Cheat Sheet
Strings in Python are immutable sequences of characters, defined by single or double quotes. They support various operations for manipulation, comparison, searching, and formatting.
Core Principles
- Strings are ordered, immutable sequences.
- Defined using single (' '), double (" "), or triple (''' ''' or """ """) quotes.
- Indexing starts at 0 for the first character.
- Slicing extracts substrings using start:stop:step.
- Strings can be concatenated (+) and repeated (*).
- Comparison operators (>, <, >=, <=, ==, !=) work lexicographically.
- Strings have built-in methods for manipulation and analysis.
- String formatting allows embedding values into strings.
Action Steps
- Create strings using quotes: `my_string = 'Hello'` or `my_string = "World"`.
- Access characters using index: `my_string[0]`.
- Extract substrings using slicing: `my_string[1:4]`.
- Combine strings: `str1 + str2`.
- Repeat strings: `str1 * 3`.
- Check for substring presence: `'sub' in my_string`.
- Use string methods like `.upper()`, `.lower()`, `.find()`, `.replace()`.
- Format strings using f-strings or the `%` operator.
Key Terms
- String: An immutable sequence of characters.
- Immutable: Cannot be changed after creation.
- Indexing: Accessing individual characters using their position (starting from 0).
- Slicing: Extracting a portion (substring) of a string using a range.
- Concatenation: Joining two or more strings together.
- Lexicographical: Alphabetical order, comparing strings based on ASCII values.
- Traversal: Iterating through each character of a string, typically using a loop.
- Substring: A sequence of characters within a larger string.
Pro Tips
- Use f-strings (formatted string literals) for modern and readable string formatting: `f'Hello, {name}!'`.
- Remember strings are immutable; operations create new strings, they don't modify existing ones.
- Use `.find()` for searching; it returns -1 if not found, while `.index()` raises an error.
- Be mindful of case sensitivity in string comparisons and searches.
- Triple quotes are ideal for multi-line strings or docstrings.
Pitfalls to Avoid
- Attempting to modify a string in place (e.g., `my_string[0] = 'H'`) will cause a TypeError.
- Off-by-one errors in slicing due to the exclusive nature of the end index.
- Confusing `.find()` (returns -1) with `.index()` (raises ValueError).
- Case sensitivity issues in comparisons and method calls.
- Forgetting that string methods often return a *new* string, not modify the original.
Real World Examples
- User Input Validation: Checking if user input is a valid email format using `.endswith('@example.com')` or checking if a password meets length requirements.
- Text Processing: Parsing log files, extracting data from text documents, or cleaning user-generated content using methods like `.split()`, `.strip()`, and `.replace()`.
- Displaying Information: Creating formatted output messages, reports, or user interfaces using string formatting (f-strings, %).
- Data Transformation: Converting text to uppercase/lowercase (`.upper()`, `.lower()`), capitalizing words (`.title()`), or standardizing text formats.
More like this