All chapters in this track
- 011. Variables, Types & Operators
- 022. Strings
- 033. Lists
- 044. Tuples, Sets & Dicts
- 055. Control Flow
- 066. Error Handling
- 077. Functions & Lambdas
- 088. Comprehensions
- 099. Built-in Functions
- 1010. Type Hints (3.10+)
- 1111. Classes & Dataclasses
- 1212. Iterators & Generators
- 1313. DSA Standard Library
- 1414. Python 3.9–3.11 Features for DSA
- 1515. DSA Idioms & Gotchas
- 1616. Master Quick Reference
Chapter 2 of 16
2. Strings
Tutorial
Strings are immutable — every "modification" creates a new string. Never concatenate in a loop with +=; always use "".join(list).
s = "Hello, World!"
# --- Creation ---
s1 = 'single or double quotes' # identical
s2 = """multi
line""" # triple quotes for multi-line strings
# --- Strings are immutable — mutate via list, then rejoin ---
chars = list(s) # convert to mutable list
chars[0] = "h"
s = "".join(chars) # convert back — O(n)
# --- Slicing ---
s[0] # 'H'
s[-1] # '!'
s[7:12] # 'World'
s[::-1] # '!dlroW ,olleH' (reversed copy)
# --- Common methods ---
s.lower() # 'hello, world!'
s.upper() # 'HELLO, WORLD!'
s.strip() # strip leading/trailing whitespace
s.lstrip() # strip left only
s.rstrip() # strip right only
s.split(",") # ['Hello', ' World!']
",".join(["a","b","c"]) # 'a,b,c'
s.replace("World","DSA")# 'Hello, DSA!'
s.find("World") # 7 (-1 if not found)
s.count("l") # 3
"World" in s # True
# Python 3.9+: removeprefix / removesuffix
"test_hello".removeprefix("test_") # 'hello'
"hello_test".removesuffix("_test") # 'hello'
# --- f-strings (3.12: improved = debugging) ---
x = 42
f"value = {x}" # 'value = 42'
f"value = {x!r}" # 'value = 42' (repr)
f"{x = }" # 'x = 42' (3.8+: = for debugging)
f"{x:.2f}" # '42.00' (format spec)
# --- Character ↔ ASCII ---
ord('a') # 97
chr(97) # 'a'
ord('b') - ord('a') # 1 (index in alphabet)
# --- String building (O(n), not O(n²)) ---
# ❌ result = ""; for c in chars: result += c → O(n²)
# ✅
result = "".join(chars) # O(n)
result = "".join(str(x) for x in nums)
# --- Frequency array for lowercase letters ---
def char_freq(s: str) -> list[int]:
freq = [0] * 26
for c in s:
freq[ord(c) - ord('a')] += 1
return freq
# --- Palindrome / anagram ---
s[::-1] == s # is palindrome (simple)
def is_palindrome(s: str) -> bool:
s = s.lower()
return s == s[::-1]
from collections import Counter
Counter(s) == Counter(t) # is anagram
def is_anagram(s: str, t: str) -> bool:
return Counter(s) == Counter(t)
Reference
| Method | Returns | Notes |
|---|---|---|
s.lower() / s.upper() | str | New string |
s.strip(chars) | str | Strips ends |
s.split(sep) | list[str] | sep=None splits on whitespace |
sep.join(lst) | str | Use instead of += |
s.find(sub) | int | -1 if missing |
s.index(sub) | int | ValueError if missing |
s.replace(old,new) | str | |
s.count(sub) | int | |
s.startswith(p) | bool | |
s.endswith(p) | bool | |
s.isalpha() / .isdigit() / .isalnum() / .isspace() | bool | |
s.removeprefix(p) | str | 3.9+ |
s.removesuffix(p) | str | 3.9+ |
ord(c) / chr(n) | int / str | |
s[i:j:step] | str | New string; s[::-1] reverses |