Strings
String Basics
Creating and using strings
Interview: Very common in interviews
Strings in Python are immutable sequences of Unicode characters. They support indexing, slicing, iteration, and a rich set of built-in methods. Understanding string immutability and memory behavior is crucial for writing efficient code.
Creating Strings
- Single quotes:
'hello'— use when string contains double quotes - Double quotes:
"hello"— use when string contains single quotes - Triple quotes:
'''...'''or"""..."""— multi-line strings and docstrings - Raw strings:
r"path\to\file"— backslashes treated literally - Byte strings:
b"hello"— bytes, not text
Immutability
Strings cannot be modified in place. Any operation that appears to modify a string actually creates a new string object. This has performance implications for repeated concatenation.
String Interning
Python automatically interns (caches) small strings and identifiers. Two string literals with the same value may share the same object in memory. Use is to check identity, == for value equality.
Common Operations
len(s)— string lengths[i]— indexing (0-based, negative from end)s[start:stop:step]— slicingx in s— substring membership test (O(n))s + t— concatenation (creates new string)s * n— repetition
Performance Tip
Never build strings with += in a loop — it creates a new string object each time (O(n²) total). Instead, use "".join(list_of_parts) which is O(n).
Use Cases
Text processing and data cleaning
Building dynamic strings efficiently with join()
Working with file paths using raw strings
Multi-line strings for templates and docstrings
Common Mistakes
Trying to modify a string in place (s[0] = "x" raises TypeError)
Building strings with += in a loop (O(n²) performance)
Confusing raw strings with regular strings in regex patterns
Not understanding string interning — use == for comparison, not is