Topic 29 of 64
String
Overview
Strings in Python are immutable sequences of Unicode characters. Every string method returns a new string. Mastering built-in string methods eliminates the need for manual character parsing in most real-world tasks.
Syntax
python
s = "Hello, World!"
s.upper() # "HELLO, WORLD!"
s.lower() # "hello, world!"
s.strip() # removes leading/trailing whitespace
s.replace("World", "Python") # "Hello, Python!"
s.split(", ") # ["Hello", "World!"]
s.startswith("He") # True
s.find("World") # 7 (index)
len(s) # 13Common Pitfalls
- Strings are immutable — s[0] = 'H' raises TypeError. Use replace() or convert to list.
- s.find() returns -1 if not found; s.index() raises ValueError — choose based on whether absence is expected.
- Interview tip: Know the difference between join and split: ', '.join(['a','b','c']) → 'a, b, c'.
Real-World Example
Clean and normalize user input from a form submission
example
python
def normalize_email(email: str) -> str:
return email.strip().lower().replace(" ", "")
raw = " Alice@EXAMPLE.COM "
clean = normalize_email(raw)
print(clean) # "alice@example.com"