Bird
Raised Fist0
Pandasdata~20 mins

str.strip() for whitespace in Pandas - Practice Problems & Coding Challenges

Choose your learning style10 modes available
Challenge - 5 Problems
🎖️
Whitespace Stripping Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate
2:00remaining
Output of str.strip() on pandas Series with whitespace
What is the output of the following code?
import pandas as pd
s = pd.Series(['  apple ', ' banana', 'cherry  ', '  date  '])
result = s.str.strip()
print(result.tolist())
Pandas
import pandas as pd
s = pd.Series(['  apple ', ' banana', 'cherry  ', '  date  '])
result = s.str.strip()
print(result.tolist())
A[' apple', 'banana', 'cherry ', 'date']
B['apple', 'banana', 'cherry', 'date']
C['apple ', ' banana', 'cherry', 'date ']
D[' apple ', ' banana', 'cherry ', ' date ']
Attempts:
2 left
💡 Hint
str.strip() removes spaces from both ends of each string in the Series.
❓ data_output
intermediate
2:00remaining
Count of strings after stripping whitespace
After stripping whitespace from the Series below, how many strings start with the letter 'b'?
import pandas as pd
s = pd.Series(['  apple ', ' banana', 'blueberry  ', '  date  ', '  berry'])
stripped = s.str.strip()
count_b = stripped.str.startswith('b').sum()
print(count_b)
Pandas
import pandas as pd
s = pd.Series(['  apple ', ' banana', 'blueberry  ', '  date  ', '  berry'])
stripped = s.str.strip()
count_b = stripped.str.startswith('b').sum()
print(count_b)
A3
B2
C1
D4
Attempts:
2 left
💡 Hint
Check which strings start with 'b' after removing spaces.
🔧 Debug
advanced
2:00remaining
Identify the error in using str.strip() on a non-string column
What error will this code raise?
import pandas as pd
df = pd.DataFrame({'numbers': [1, 2, 3, 4]})
df['clean'] = df['numbers'].str.strip()
Pandas
import pandas as pd
df = pd.DataFrame({'numbers': [1, 2, 3, 4]})
df['clean'] = df['numbers'].str.strip()
AKeyError: 'str'
BNo error, returns original numbers
CTypeError: strip() argument must be str, not int
DAttributeError: Can only use .str accessor with string values!
Attempts:
2 left
💡 Hint
The .str accessor only works on string data.
🚀 Application
advanced
2:00remaining
Using str.strip() to clean a DataFrame column before analysis
You have a DataFrame with a column 'city' containing city names with extra spaces. Which code snippet correctly cleans the 'city' column by removing leading and trailing spaces?
import pandas as pd
df = pd.DataFrame({'city': [' New York ', 'Los Angeles ', ' Chicago', 'Houston ']})
Pandas
import pandas as pd
df = pd.DataFrame({'city': [' New York ', 'Los Angeles ', ' Chicago', 'Houston ']})
Adf['city'] = df['city'].apply(strip())
Bdf['city'] = df['city'].strip()
Cdf['city'] = df['city'].str.strip()
Ddf['city'] = df['city'].map(str.strip)
Attempts:
2 left
💡 Hint
Use the pandas string accessor for element-wise string operations.
🧠 Conceptual
expert
2:00remaining
Understanding str.strip() behavior with custom characters
What will be the output of this code?
import pandas as pd
s = pd.Series(['xxapplexx', 'xbanana', 'cherryxx', 'xxdate'])
result = s.str.strip('x')
print(result.tolist())
Pandas
import pandas as pd
s = pd.Series(['xxapplexx', 'xbanana', 'cherryxx', 'xxdate'])
result = s.str.strip('x')
print(result.tolist())
A['apple', 'banana', 'cherry', 'date']
B['xxapplexx', 'xbanana', 'cherryxx', 'xxdate']
C['applexx', 'banana', 'cherry', 'date']
D['apple', 'banana', 'cherryxx', 'date']
Attempts:
2 left
💡 Hint
str.strip(chars) removes all characters in 'chars' from both ends until a different character is found.

Practice

(1/5)
1. What does the pandas str.strip() method do when applied to a Series of strings?
easy
A. Removes spaces from the start and end of each string
B. Removes all spaces inside each string
C. Converts all characters to uppercase
D. Splits strings into lists of words

Solution

  1. Step 1: Understand the purpose of str.strip()

    This method removes whitespace characters only from the beginning and end of each string in the Series.
  2. Step 2: Differentiate from other string methods

    Unlike str.replace() or str.upper(), it does not change spaces inside the string or letter cases.
  3. Final Answer:

    Removes spaces from the start and end of each string -> Option A
  4. Quick Check:

    str.strip() removes edge spaces [OK]
Hint: Remember: strip trims only start/end spaces, not inside [OK]
Common Mistakes:
  • Thinking it removes spaces inside the string
  • Confusing with uppercasing or splitting
  • Assuming it removes all whitespace characters everywhere
2. Which of the following is the correct syntax to remove leading and trailing spaces from a pandas Series named data?
easy
A. data.strip()
B. data.strip.str()
C. data.str.strip()
D. strip(data)

Solution

  1. Step 1: Recall pandas string accessor usage

    To use string methods on a Series, you must use the .str accessor before the method.
  2. Step 2: Identify correct method call

    The correct syntax is data.str.strip(). Other options either miss the accessor or have wrong order.
  3. Final Answer:

    data.str.strip() -> Option C
  4. Quick Check:

    Use .str before string methods [OK]
Hint: Use .str before string methods on Series [OK]
Common Mistakes:
  • Calling strip() directly on Series without .str
  • Using wrong order like .strip.str()
  • Trying to call strip as a standalone function
3. Given the pandas Series:
import pandas as pd
data = pd.Series(['  apple ', 'banana  ', '  cherry'])
cleaned = data.str.strip()

What is the output of print(cleaned.tolist())?
medium
A. [' apple', 'banana ', ' cherry']
B. ['apple', 'banana', 'cherry']
C. ['apple ', ' banana', 'cherry']
D. ['apple', ' banana ', 'cherry']

Solution

  1. Step 1: Understand what str.strip() does on each string

    It removes spaces from the start and end of each string, so ' apple ' becomes 'apple', 'banana ' becomes 'banana', and ' cherry' becomes 'cherry'.
  2. Step 2: Convert the cleaned Series to a list

    Using tolist() shows the cleaned strings without leading or trailing spaces.
  3. Final Answer:

    ['apple', 'banana', 'cherry'] -> Option B
  4. Quick Check:

    strip removes edge spaces, output clean list [OK]
Hint: strip removes spaces only at string edges [OK]
Common Mistakes:
  • Expecting spaces inside strings to be removed
  • Confusing strip with replace or split
  • Not converting Series to list before printing
4. You run this code:
import pandas as pd
s = pd.Series(['  dog', 'cat  ', '  bird  '])
s_clean = s.strip()

But get an error. What is the problem?
medium
A. You should use s.str.strip() instead of s.strip()
B. You forgot to import pandas
C. The Series contains numbers, so strip won't work
D. strip() does not remove spaces

Solution

  1. Step 1: Identify the error cause

    Calling strip() directly on a pandas Series causes an AttributeError because Series objects do not have a direct strip() method.
  2. Step 2: Correct method usage

    Use the string accessor .str to apply string methods on Series: s.str.strip().
  3. Final Answer:

    You should use s.str.strip() instead of s.strip() -> Option A
  4. Quick Check:

    Use .str before string methods on Series [OK]
Hint: Always use .str before string methods on Series [OK]
Common Mistakes:
  • Calling strip() directly on Series
  • Assuming strip works on non-string data
  • Ignoring error messages about missing method
5. You have a DataFrame df with a column 'Name' containing names with extra spaces:
import pandas as pd
df = pd.DataFrame({'Name': ['  Mary Ann  ', 'Bob', '  Charlie  ', 'David ']})

How do you clean the 'Name' column to remove spaces only at the start and end, keeping spaces inside names intact?
hard
A. df['Name'] = df['Name'].lstrip().str.rstrip()
B. df['Name'] = df['Name'].str.replace(' ', '')
C. df['Name'] = df['Name'].strip(' ')
D. df['Name'] = df['Name'].str.strip()

Solution

  1. Step 1: Understand the goal

    We want to remove only spaces at the start and end of each string, not spaces inside the names (e.g., keep 'Mary Ann' intact).
  2. Step 2: Choose the correct method

    str.strip() removes leading and trailing whitespace. df['Name'] = df['Name'].str.strip() uses it correctly. df['Name'] = df['Name'].lstrip().str.rstrip() fails with AttributeError (no .str before lstrip()). df['Name'] = df['Name'].str.replace(' ', '') removes all spaces (e.g., 'MaryAnn'). df['Name'] = df['Name'].strip(' ') fails (no .str accessor).
  3. Final Answer:

    df['Name'] = df['Name'].str.strip() -> Option D
  4. Quick Check:

    Use str.strip() to clean edges only [OK]
Hint: Use str.strip() to clean edges, not inside spaces [OK]
Common Mistakes:
  • Using str.replace(' ', '') removes all spaces, including inside names
  • Forgetting .str accessor before lstrip() when chaining methods
  • Calling strip() directly on Series without .str accessor
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard