Vasu Patel logoVasu Patel
← Python Syntax & DSA Reference
All chapters in this track
  1. 011. Variables, Types & Operators
  2. 022. Strings
  3. 033. Lists
  4. 044. Tuples, Sets & Dicts
  5. 055. Control Flow
  6. 066. Error Handling
  7. 077. Functions & Lambdas
  8. 088. Comprehensions
  9. 099. Built-in Functions
  10. 1010. Type Hints (3.10+)
  11. 1111. Classes & Dataclasses
  12. 1212. Iterators & Generators
  13. 1313. DSA Standard Library
  14. 1414. Python 3.9–3.11 Features for DSA
  15. 1515. DSA Idioms & Gotchas
  16. 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

MethodReturnsNotes
s.lower() / s.upper()strNew string
s.strip(chars)strStrips ends
s.split(sep)list[str]sep=None splits on whitespace
sep.join(lst)strUse instead of +=
s.find(sub)int-1 if missing
s.index(sub)intValueError 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)str3.9+
s.removesuffix(p)str3.9+
ord(c) / chr(n)int / str
s[i:j:step]strNew string; s[::-1] reverses