Skip to Content
Course content

20: String Methods for Searching and Replacing

Click on the "Edit" button in the top corner of the screen to edit your slide content.

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.

Rating
0 0

There are no comments for now.

to be the first to leave a comment.