Python
Completed
-
Section 1: Getting Started
-
Section 2: Core Syntax and Data Types
-
Section 3: Collections
-
39: Set Operations: Union, Intersection, Difference
-
Section 4: Control Flow
-
Section 5: Functions
-
Section 6: Turtle Graphics and Early Practice Projects
-
Section 7: Working with Files and I/O
-
Section 8: Regular Expressions
-
Section 9: Object-Oriented Python
-
Section 10: Error Handling
-
Section 11: Modules and Packages
-
Section 12: Iterators, Generators, and Functional Tools
-
Section 13: Decorators and Metaprogramming
-
Section 14: Concurrency and Parallelism
-
Section 15: Working with Dates, Times, and Numbers
-
Section 16: Standard Library Deep Dive I: Data Structures
-
Section 17: Standard Library Deep Dive II: System and Introspection
-
Section 18: Standard Library Deep Dive III: Security and Encoding
-
Section 19: Standard Library Deep Dive IV: Text and Data Utilities
-
Section 20: Networking and Web Basics
-
Section 21: Working with Databases
-
Section 22: Testing and Quality
-
Section 23: Advanced Typing
-
Section 24: Context Managers and Resource Handling
-
Section 25: Text, Unicode, and Binary Data
-
Section 26: More Functional and Iteration Tools
-
Section 27: Data Validation and Configuration
-
Section 28: Working with Images and Media
-
Section 29: Property-Based and Documentation Testing
-
Section 30: Packaging and Deployment
-
Section 31: Performance and Internals
-
Section 32: Design Patterns in Python
-
Section 33: GUI Programming
-
Section 34: Security Basics
-
Section 35: Data Structures and Algorithms
-
Section 36: Practical Projects
-
Section 37: Capstone Projects
-
Section 38: Interview and Algorithm Practice
-
Section 39: Writing Idiomatic Python
20: String Methods for Searching and Replacing
I've seen this exact bug countless times during code reviews: a developer calls a method to clean up a string, but when they print the string on the next line, it's as if nothing happened. They usually assume they did something wrong with the method call, but the reality is they're fighting a fundamental property of Python.
The myth that .replace() changes your original string
When you're coming from other languages, or even just working with Python lists, you expect a method to modify the object it's called on. You might try something like this to clean up a messy product ID:
product_id = " PROD_99_OLD "
product_id.replace("OLD", "NEW").strip()
print(product_id)
# You expect "PROD_99_NEW", but you get " PROD_99_OLD "
It feels like the code "ran," but the result vanished into the void. This happens because strings in Python are immutable. Once a string is created in memory, it cannot be changed. Not a single character. When you call .replace(), Python isn't editing your string; it's building a brand new string from scratch and handing it back to you.
Embracing the return value: How strings actually work
To actually "change" a string, you have to catch that new version Python hands back to you by assigning it to a variable. I usually just overwrite the original variable name to keep things clean.
product_id = " PROD_99_OLD "
# Catch the return value!
product_id = product_id.replace("OLD", "NEW").strip()
print(product_id) # Now we have "PROD_99_NEW"
Since these methods return strings, you can chain them together—as I did above with .replace().strip()—creating a little assembly line of transformations.
Hunting for data with .find() and .count()
Sometimes you don't want to change the string; you just need to know if something is in there and where it is. While the in keyword is great for a simple True/False check, .find() is what you use when you need the exact index.
log_entry = "ERROR: Disk failure at 12:00PM"
position = log_entry.find("Disk")
print(position) # Output: 7
One thing to watch out for: if .find() can't find the substring, it returns -1. This is a bit old-school, but it's how Python tells you "not found" without crashing your program. If you absolutely need the code to crash (raise an exception) when the string isn't found, use .index() instead. I personally prefer .find() because I'd rather handle a -1 than wrap my whole block in a try-except.
If you just need to know how many times a word appears—say, counting how many times a user mentioned "Python" in a forum post—use .count():
comment = "Python is great, but Python can be tricky for beginners."
print(comment.count("Python")) # Output: 2
Quick checks with .startswith() and .endswith()
You could use slicing to check the beginning or end of a string, but that's clumsy. Python gives us .startswith() and .endswith(), which make your code read like English. This is incredibly useful for filtering files or validating URLs.
filename = "report_2023_final.pdf"
if filename.endswith(".pdf"):
print("This is a PDF document.")
if filename.startswith("report"):
print("This is a report file.")
Pro tip: these methods can actually take a tuple of strings. If you want to check if a file is either a .jpg or a .png, you don't need two if statements. Just do filename.endswith((".jpg", ".png")).
📋 Practical Task
Sanitizing a Messy CSV Header Row
You have been given a raw header string extracted from a legacy CSV file. It is filled with inconsistent spacing, ugly delimiters, and hidden "trash" characters. Your goal is to clean this string so it can be used in a database.
The Input String:
raw_header = " USER_ID | USER_NAME | EMAIL_ADDRESS | LAST_LOGIN_DATE "
Requirements:
- Remove the leading and trailing whitespace.
- Replace all occurrences of the pipe character (
|) with a comma (,). - Ensure there are no double spaces between the columns (replace
" , "with","). - Verify that the cleaned string starts with
"USER_ID"and ends with"DATE", printing "Validation Successful" if it does.
Write a Python script that transforms raw_header into the cleaned format and performs the validation check.
There are no comments for now.