Skip to Content
Course content

29: Practice Exercise: String Manipulation Challenges

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

How do I clean up a messy string that has weird spacing or mixed separators?

I see this all the time when people start working with real-world data. You'll get a string from a user or an API that looks like " python, javascript , ruby, sql " and it's a nightmare to parse. The trick is to avoid trying to do everything in one go.

Don't just split by the comma and call it a day, because you'll end up with leading and trailing spaces in your results. Instead, split the string and then use a list comprehension to strip() each element. It's much cleaner.

raw_tags = "  python,  javascript ,  ruby,  sql  "
# Split by comma, then strip whitespace from each resulting string
clean_tags = [tag.strip() for tag in raw_tags.split(",")]
print(clean_tags)  # ['python', 'javascript', 'ruby', 'sql']

One quick tip: if you're just dealing with random whitespace (tabs, newlines, spaces) and no commas, calling .split() without any arguments automatically handles any amount of whitespace for you.

Is there a better way to build a long string than just adding them together with +?

If you're joining two or three strings, the + operator is totally fine. But if you're inside a loop building a massive document or a CSV file, stop right there. In Python, strings are immutable. Every time you use +, Python creates a brand new string in memory. If you do that a thousand times, your performance will tank.

The "pro" way to do this is by collecting your pieces in a list and using "".join() at the very end. I've seen this literally turn a script that took minutes to run into one that takes milliseconds.

data_points = ["2023-10-01", "ERROR", "Database timeout", "User: 42"]
# Instead of using a loop with += 
# Use join to glue them together with a pipe character
log_entry = " | ".join(data_points)
print(log_entry)  # 2023-10-01 | ERROR | Database timeout | User: 42

What's the cleanest way to extract a specific part of a string when the position changes?

You might be tempted to use hard-coded index numbers—like string[7:15]—but that's a recipe for bugs the moment your input data changes slightly. When the position is dynamic, I usually rely on a combination of .find() (or .rfind() for the last occurrence) and slicing.

Let's say you're trying to grab the domain from an email address. You know the domain starts after the @ symbol, but the username length varies.

email = "software.engineer.pro@example-company.com"
at_index = email.find("@")
# We slice from the index immediately after the '@' to the end
domain = email[at_index + 1:]
print(domain)  # example-company.com

It's a simple pattern, but it's incredibly robust. Just remember that .find() returns -1 if it doesn't find the character, so in a production app, you'd want to check for that before slicing.




📋 Practical Task

Exercise: The Raw Log File Parser

You've been handed a raw string from a legacy server log. The data is messy and inconsistent. Your goal is to write a function that extracts only the timestamp and the error message from the string.

The input string:
" LOG_LEVEL: ERROR | TIME: 2023-11-15 14:30:05 | MSG: Connection failed due to timeout | CODE: 504 "

Requirements:

  • Remove the leading and trailing whitespace from the entire string.
  • Extract the timestamp (everything between TIME: and the next | ).
  • Extract the message (everything between MSG: and the next | ).
  • Return the results as a tuple: (timestamp, message).
def parse_log_entry(log_string):
    # Your code here
    pass

# Test case
raw_data = "  LOG_LEVEL: ERROR | TIME: 2023-11-15 14:30:05 | MSG: Connection failed due to timeout | CODE: 504  "
print(parse_log_entry(raw_data)) 
# Expected Output: ('2023-11-15 14:30:05', 'Connection failed due to timeout')
Rating
0 0

There are no comments for now.

to be the first to leave a comment.