Warming up the neural circuits...
By the end of this chapter you will:
Half of programming is cleaning up other people's text. User input has extra spaces, CSV files have inconsistent delimiters, and responses have weird formatting. Master string methods, and you can handle any text processing task.
# Split
text = "apple,banana,cherry"
parts = text.split(",") # ['apple', 'banana', 'cherry']
# Split on whitespace (default)
sentence = "Hello world how are you"
words = sentence.split() # ['Hello', 'world', 'how', 'are', 'you']
# rsplit — split from right
text = "one.two.three.four"
parts = text.rsplit(".", 2) # ['one.two', 'three', 'four']
# Join
words = ["Hello", "world"]
sentence = " ".join(words) # "Hello world"
csv = ",".join(["a", "b"]) # "a,b"| Method | Returns | Use when |
|---|---|---|
split(sep) | List | Parse CSV, split words |
rsplit(sep, n) | List | Split from right, limit n |
splitlines() | List | Split by newlines |
join(list) | String | Combine with separator |
# Strip whitespace
text = " hello "
print(text.strip()) # 'hello'
print(text.lstrip()) # 'hello '
print(text.rstrip()) # ' hello'
#
text = "Hello, World!"
# find — returns index or -1
print(text.find("World")) # 7
print(text.find("Python")) # -1
# index — returns index or ValueError
# Basic case
text = "Hello, World!"
print(text.lower()) # 'hello, world!'
print(text.upper()) # 'HELLO, WORLD!'
print(text.title()) # 'Hello, World!'
print
Input → Clean → Parse → Transform → Output
strip split replace join
lower find upper f-string| Mistake | Why it's wrong | Fix |
|---|---|---|
text.replace("old", "new") doesn't change text | Strings are immutable | text = text.replace(...) |
text.find("x") returns -1, not error | -1 is valid index (end) | Check if text.find("x") != -1 or use in |
"Hello" == "hello" → False | Case-sensitive comparison | Use .lower() or .casefold() |
text.strip() removes too much | Removes ALL matching chars from both ends | text.strip(" ") for spaces only |
Beginner:
"What's the difference between find() and index()?"
find()returns -1 if the substring is not found.index()raises ValueError. Usefind()when you want to check if something exists; useindex()when not finding it is an error.
"How do you split a string by multiple delimiters?"
Use
re.split():re.split(r'[,;|]', text). Or chainreplace()andsplit():text.replace(';', ',').split(',').
Senior:
split() breaks text into list. join() combines list into string.strip() removes whitespace. replace() substitutes text.find() returns -1 if not found. index() raises ValueError. in returns True/False.casefold() is better than lower() for case-insensitive comparisons.I want to…
├── Split text → text.split(",")
├── Join parts → ",".join(list)
├── Clean whitespace → text.strip()
├── Replace text → text.replace("old", "new")
├── Find text → text.find("x") or "x" in text
├── Check prefix → text.startswith("x")
├── Case-insensitive → text.casefold()
└── Count occurrences → text.count("x")What does 'hello world'.split() return?
| Method | Returns | Use when |
|---|---|---|
strip() | String | Remove whitespace both sides |
strip(chars) | String | Remove specific chars |
replace(old, new) | String | Substitute text |
replace(old, new, n) | String | Replace first n occurrences |
| Method | Returns | Use when |
|---|---|---|
find(sub) | Index or -1 | Safe search |
index(sub) | Index or ValueError | When missing is error |
sub in str | True/False | Membership check |
count(sub) | Number | Count occurrences |
startswith(s) | True/False | Check prefix |
endswith(s) | True/False | Check suffix |
Key: Use casefold() for case-insensitive comparisons, especially with international text.
"Why is casefold() better than lower() for case-insensitive comparisons?"
lower()is locale-aware and may not normalize all characters.casefold()aggressively normalizes — e.g., German 'ß' becomes 'ss'. For case-insensitive comparisons, especially with international text, usecasefold().
"What's the time complexity of in for string search?"
O(n*m) in the worst case, where n is the string length and m is the substring length. Python uses a mix of Boyer-Moore and other algorithms for practical performance. For frequent searches, consider compiling a regex pattern once.