Skip to Content
Course content

21: String Methods for Case and Whitespace

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

I was working on a script yesterday to import a list of users from a legacy CSV file, and it was a total mess. The data looked like this: " jAnE dOe ", " BOB SMITH", and " alice wonderland ". If I tried to look these users up in my database using a simple string comparison, everything failed because of a few stray spaces and inconsistent capitalization.

The Case Consistency Headache

First, I wanted to normalize these names. I figured I'd just make everything lowercase so that "Jane" and "jane" are treated as the same person. I started with a simple test:

name = "  jAnE dOe  "
print(name.lower()) 
# Output: "  jane doe  "

That worked for the letters, but the string still feels "dirty" because of those leading and trailing spaces. Now, I thought about making it look professional—like a proper name. I tried capitalize(), thinking it would fix the casing for me:

print(name.capitalize()) 
# Output: "  jane doe  "

Wait, that didn't do what I expected. It looks like capitalize() only cares about the very first character of the string. Since my string starts with a space, it "capitalized" the space (which does nothing) and forced everything else to lowercase. That's a trap I've fallen into more than once.

If I want every word to start with a capital letter, I need title():

print(name.title()) 
# Output: "  Jane Doe  "

Much better. But we still have those annoying spaces hanging around the edges.

Taming the Invisible Spaces

I could try to manually slice the string, but that's a waste of time. Python has built-in tools for this. I'll try strip(), which is the "hammer" for whitespace:

name = "  Jane Doe  "
clean_name = name.strip()
print(f"'{clean_name}'") 
# Output: 'Jane Doe'

That cleaned both ends perfectly. But sometimes, you don't want to be that aggressive. For example, if I'm parsing a file where indentation at the start of a line matters, but trailing spaces at the end are just noise, I can be more specific.

I've found that rstrip() (right strip) and lstrip() (left strip) are lifesavers when you need precision:

raw_line = "    Indented text    "
print(f"'{raw_line.rstrip()}'") # Keeps the left indent, kills the right spaces
# Output: '    Indented text'

print(f"'{raw_line.lstrip()}'") # Kills the left indent, keeps the right spaces
# Output: 'Indented text    '

Putting it all together

In a real scenario, I wouldn't call these on separate lines. I'd chain them. This is where Python feels really elegant. I can strip the whitespace first, and then apply the casing I want, all in one breath.

messy_input = "  jAnE dOe  "
# Clean the edges, then make it a title
final_name = messy_input.strip().title()
print(final_name) 
# Output: Jane Doe

Just a heads-up: remember that strings in Python are immutable. None of these methods actually change the original string; they return a brand new one. If you call name.strip() but don't assign it back to a variable, your original string stays messy.




📋 Practical Task

The User Directory Sanitizer

You've been handed a list of usernames and email addresses that were entered manually by users. They are inconsistent, full of accidental spaces, and have erratic casing. Your job is to clean them up so they can be used in a professional directory.

The Requirements:

  • Create a list called raw_data containing these three strings: " ALICE_SMITH ", " bob_jones ", and " cHarlie_Brown ".
  • Write a loop that processes each string in that list.
  • For each string:
    1. Remove all leading and trailing whitespace.
    2. Convert the entire string to lowercase (since usernames should be case-insensitive).
  • Print the cleaned usernames to the console.
Rating
0 0

There are no comments for now.

to be the first to leave a comment.