Topic 07 / 15
Strings & f-Strings
Strings Are Immutable Sequences
Strings support indexing and slicing like lists, but every “modification” returns a new string:
s = "Coding India"
s[0] # 'C'
s[-5:] # 'India'
s.upper() # 'CODING INDIA' — s itself is unchangedf-Strings — the Only Formatting You Need
name, subs = "Coding India", 10500
f"{name} has {subs} subscribers"
f"{subs:,}" # '10,500' — thousands separator
f"{3.14159:.2f}" # '3.14' — 2 decimal places
f"{0.876:.1%}" # '87.6%' — percentage
f"{42:>8}" # ' 42' — right-align in 8 chars
f"{name=}" # "name='Coding India'" — debug shorthandAny expression works inside the braces: f"total: {price * qty}".
The Methods You’ll Use Every Day
" hello ".strip() # 'hello'
"Hello".lower() / .upper()
"hello world".title() # 'Hello World'
"hello".replace("l", "L") # 'heLLo'
"hello".startswith("he") # True
"data.csv".endswith(".csv") # True
"hello".find("ll") # 2 (or -1 if missing)
"hello".count("l") # 2
"42".isdigit() # TrueSplit & Join — Text ⇄ Lists
"django,react,fastapi".split(",")
# ['django', 'react', 'fastapi']
" multiple spaces ".split() # splits on any whitespace
# ['multiple', 'spaces']
", ".join(["django", "react"]) # 'django, react'
"-".join(str(n) for n in [2, 0, 2, 6]) # '2-0-2-6'Note the direction: join is a string method that takes a list — the separator comes first.
Multiline Strings & Raw Strings
query = """
SELECT name, score
FROM students
WHERE score > 80
"""
path = r"C:\Users\new_folder" # r'' = raw — backslashes left alone
pattern = r"\d{4}-\d{2}-\d{2}" # essential for regexBuilding Strings in Loops
Because strings are immutable, += in a loop copies the whole string every iteration. Collect parts in a list and join once:
parts = []
for row in rows:
parts.append(render(row))
html = "".join(parts) # one allocation, fast