Topic 12 of 64
String Methods & Formatting
Overview
Python's string type comes with powerful built-in methods for text manipulation. f-strings (Python 3.6+) provide the most readable way to format strings — mastering both is essential for clean Python code.
Syntax
python
s = " Hello, World! "
# Case
s.upper() # " HELLO, WORLD! "
s.lower() # " hello, world! "
s.title() # " Hello, World! "
s.capitalize() # " hello, world! " → capitalize first char
# Stripping
s.strip() # "Hello, World!"
s.lstrip() # "Hello, World! "
s.rstrip() # " Hello, World!"
# Searching
s.find("World") # 8 (index or -1)
s.index("World") # 8 (raises ValueError if not found)
s.count("l") # 3
s.startswith(" ") # True
s.endswith("! ") # True
s.replace("World", "Python") # " Hello, Python! "
# Splitting
"a,b,c".split(",") # ["a", "b", "c"]
" a b ".split() # ["a", "b"] (splits on whitespace)
", ".join(["a","b"]) # "a, b"
# f-string formatting
name, amount = "Priya", 1234567.89
f"{name:>20}" # right-align in 20 chars
f"{amount:,.2f}" # "1,234,567.89"
f"{amount:.0f}" # "1234568"
f"{'★' * 5}" # "★★★★★"Common Pitfalls
- str.find() returns -1 if not found; str.index() raises ValueError — choose based on whether 'not found' is an error.
- Strings are immutable — all string methods return NEW strings, they never modify the original.
- Interview tip: f-strings are faster than .format() and % formatting — always prefer f-strings for Python 3.6+.
Real-World Example
A report generator with formatted output:
example
python
def format_sales_report(sales_data: list[dict]) -> str:
lines = []
lines.append("=" * 50)
lines.append(f"{'SALES REPORT':^50}") # centered
lines.append("=" * 50)
total = 0
for item in sales_data:
name = item["product"]
amount = item["amount"]
total += amount
# Left-align name, right-align amount
lines.append(f"{name:<30} ₹{amount:>10,.0f}")
lines.append("-" * 50)
lines.append(f"{'TOTAL':<30} ₹{total:>10,.0f}")
lines.append("=" * 50)
return "
".join(lines)
report = format_sales_report([
{"product": "MacBook Pro M3", "amount": 134900},
{"product": "iPhone 15 Pro", "amount": 134900},
{"product": "AirPods Pro", "amount": 24900},
])
print(report)