Back to Notes

Python String Functions for DSA

Python String Functions for DSA

Quick reference for string operations commonly used in LeetCode / interview problems.


1. Case Conversion

s = "Hello World"

s.lower()        # "hello world"
s.upper()        # "HELLO WORLD"
s.swapcase()     # "hELLO wORLD"
s.capitalize()   # "Hello world"  (only first char uppercased)
s.title()        # "Hello World"  (each word capitalized)

2. Check / Validate

s = "Hello123"

s.isalpha()      # False — only alphabetic?
s.isdigit()      # False — only digits?
s.isalnum()      # True  — only letters + digits?
s.isspace()      # False — only whitespace?
s.islower()      # False — all lowercase?
s.isupper()      # False — all uppercase?

# Common DSA pattern: filter alphanumeric
filtered = [c.lower() for c in s if c.isalnum()]

3. Search & Find

s = "abcabc"

s.find("b")       # 1  — first index, -1 if not found
s.rfind("b")      # 4  — last index, -1 if not found
s.index("b")      # 1  — like find() but raises ValueError if not found
s.count("a")      # 2  — count occurrences
s.startswith("ab") # True
s.endswith("bc")   # True

4. Modify / Clean

s = "  hello  "

s.strip()         # "hello"   — remove leading + trailing whitespace
s.lstrip()        # "hello  " — remove leading only
s.rstrip()        # "  hello" — remove trailing only
s.strip("x")      # remove specific char from both ends

s = "hello"
s.replace("l", "r")   # "herro"
s.replace("l", "", 1) # "helo" — replace first occurrence only

5. Split & Join

s = "a,b,c"

s.split(",")         # ["a", "b", "c"]
s.split(",", 1)      # ["a", "b,c"] — limit splits
s.split()            # splits on any whitespace, removes empty strings

"hello world".split()  # ["hello", "world"]

# Join — most common in DSA
"-".join(["a", "b", "c"])   # "a-b-c"
"".join(["a", "b", "c"])    # "abc"
" ".join(reversed("abc"))   # "c b a"

6. Pad & Align

"42".zfill(5)        # "00042" — zero-pad (useful for binary problems)
"hi".ljust(5)        # "hi   "
"hi".rjust(5)        # "   hi"
"hi".center(6)       # "  hi  "

7. Encoding / Ord / Chr

ord("a")    # 97  — char to ASCII
ord("A")    # 65
chr(97)     # "a" — ASCII to char

# Common DSA pattern: map letter to index
index = ord(c) - ord("a")   # 'a'->0, 'b'->1, ..., 'z'->25

8. Slicing

s = "abcdef"

s[1:4]      # "bcd"
s[::-1]     # "fedcba" — reverse string
s[::2]      # "ace"    — every other char
s[-3:]      # "def"    — last 3 chars
s[:-3]      # "abc"    — all except last 3

9. String Formatting

# f-string (most common in modern Python)
name = "Vatsal"
f"Hello {name}"        # "Hello Vatsal"
f"{42:05d}"            # "00042" — zero-padded int
f"{3.14:.2f}"          # "3.14"  — 2 decimal places
f"{'hi':>10}"          # "        hi" — right align in width 10

# bin / hex / oct
bin(10)   # "0b1010"
hex(255)  # "0xff"
oct(8)    # "0o10"

int("1010", 2)   # 10  — binary string to int
int("ff", 16)    # 255 — hex string to int

10. Common DSA Patterns

# Check palindrome
s == s[::-1]

# Frequency count
from collections import Counter
Counter("aabbc")   # Counter({'a': 2, 'b': 2, 'c': 1})

# Sorted string (anagram check)
sorted("listen") == sorted("silent")   # True

# Sliding window on string
# Use two pointers + dict/Counter for window freq tracking

# Convert string to list for in-place-style edits
chars = list(s)
chars[0] = "X"
result = "".join(chars)

Complexity Reference

OperationTime
s[i] index accessO(1)
s[i:j] sliceO(k) where k = slice length
s + t concatenationO(n+m)
"".join(list)O(n)
s.find() / in operatorO(n·m) worst case
sorted(s)O(n log n)
Counter(s)O(n)

Prefer "".join(list) over repeated += for building strings — += is O(n²) in a loop.