String cleaning (strip, lower, replace) in Data Analysis Python - Time & Space Complexity
We want to understand how the time to clean strings grows as we handle more data.
How does the work change when we clean many strings or longer strings?
Analyze the time complexity of the following code snippet.
def clean_strings(strings):
cleaned = []
for s in strings:
s = s.strip()
s = s.lower()
s = s.replace(' ', '_')
cleaned.append(s)
return cleaned
This code cleans a list of strings by removing spaces at ends, making all letters lowercase, and replacing spaces inside with underscores.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Looping over each string in the list.
- How many times: Once for each string in the input list.
- Inside the loop, string methods operate on each string's characters.
- The dominant work depends on the total number of characters processed.
As we add more strings or longer strings, the work grows roughly with the total characters.
| Input Size (n strings) | Approx. Operations (characters processed) |
|---|---|
| 10 strings, avg 5 chars | ~50 |
| 100 strings, avg 5 chars | ~500 |
| 1000 strings, avg 5 chars | ~5000 |
Pattern observation: The work grows linearly with the total number of characters across all strings.
Time Complexity: O(n * m)
This means the time grows with the number of strings (n) times the average length of each string (m).
[X] Wrong: "String cleaning takes the same time no matter how long the strings are."
[OK] Correct: Each string method looks at every character, so longer strings take more time to process.
Understanding how string operations scale helps you explain your code's efficiency clearly and confidently.
"What if we used a regular expression to replace spaces instead of the replace method? How would the time complexity change?"
Practice
strip() method do to a string in Python?Solution
Step 1: Understand the purpose of strip()
Thestrip()method removes whitespace characters from the beginning and end of a string.Step 2: Compare with other methods
lower()changes case,replace()changes parts of the string, and splitting creates lists, so they do not matchstrip().Final Answer:
Removes spaces from the start and end of the string -> Option BQuick Check:
strip() = remove spaces [OK]
- Thinking strip() changes case
- Confusing strip() with replace()
- Assuming strip() splits strings
text?Solution
Step 1: Identify the correct method for replacement
Thereplace()method is used to change parts of a string by specifying the old and new substrings.Step 2: Check the syntax
The syntax isstring.replace(old, new). So, to replace 'cat' with 'dog', it istext.replace('cat', 'dog').Final Answer:
text.replace('cat', 'dog') -> Option DQuick Check:
replace(old, new) = correct syntax [OK]
- Swapping old and new strings
- Using strip() or lower() instead of replace()
- Wrong method call syntax
text = ' Hello World '
cleaned = text.strip().lower().replace('world', 'there')
print(cleaned)Solution
Step 1: Apply strip() to remove spaces
The original string has spaces at start and end.strip()removes them, so string becomes 'Hello World'.Step 2: Apply lower() to convert to lowercase
Converts 'Hello World' to 'hello world'.Step 3: Apply replace() to change 'world' to 'there'
Replaces 'world' with 'there', resulting in 'hello there'.Final Answer:
'hello there' -> Option AQuick Check:
strip + lower + replace = 'hello there' [OK]
- Forgetting strip() removes spaces
- Not converting to lowercase before replace
- Replacing with wrong case
text = ' Data Science ' cleaned = text.strip.lower() print(cleaned)
Solution
Step 1: Identify method call syntax
Methods likestrip()require parentheses to be called. Here,stripis used without parentheses, so it is a method object, not called.Step 2: Understand the error
Trying to calllower()on a method object causes an error becausestripwas not executed.Final Answer:
strip() is missing parentheses -> Option CQuick Check:
Method calls need () [OK]
- Forgetting parentheses on methods
- Thinking order of strip and lower causes error
- Assuming replace() is required
codes = [' AB123 ', 'cd456', ' EF789', 'GH 012 ']
Which code snippet correctly cleans all codes by removing leading and trailing spaces and converting to lowercase?
Solution
Step 1: Understand the goal
We want to remove leading and trailing whitespace from each code and convert all letters to lowercase, preserving internal spaces.Step 2: Analyze each option
cleaned = [code.strip().lower() for code in codes]usesstrip()to remove leading/trailing whitespace thenlower()to convert case. Correct (e.g., 'GH 012 ' -> 'gh 012').cleaned = [code.lower() for code in codes]only converts to lowercase, leaves leading/trailing spaces. Incorrect.cleaned = [code.replace(' ', '').lower() for code in codes]removes all spaces including internal ('GH 012 ' -> 'gh012'). Incorrect.cleaned = [code.strip().replace(' ', '').lower() for code in codes]replace()removes internal spaces afterstrip(). Incorrect.Final Answer:
cleaned = [code.strip().lower() for code in codes] -> Option AQuick Check:
strip then lower cleans codes [OK]
- Forgetting strip() and only using lower() leaves spaces
- Using replace(' ', '') removes internal spaces
- Redundant replace after strip removes internal spaces
Ready to prove it?
Pass the test and this pattern moves unknown
