Challenge - 5 Problems
String Length Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of str.len() on a pandas Series
What is the output of the following code snippet?
Pandas
import pandas as pd s = pd.Series(['apple', 'banana', 'cherry', None]) result = s.str.len() print(result)
Attempts:
2 left
💡 Hint
Remember that missing values in pandas string operations usually result in NaN, not zero or None.
✗ Incorrect
The str.len() method returns the length of each string in the Series. For missing values (None), it returns NaN. The dtype is float64 because NaN is a float.
❓ data_output
intermediate1:30remaining
Count of strings with length greater than 4
Given the Series below, what is the count of strings with length greater than 4?
Pandas
import pandas as pd s = pd.Series(['dog', 'elephant', 'cat', 'lion', 'tiger', None]) count = (s.str.len() > 4).sum() print(count)
Attempts:
2 left
💡 Hint
Check which strings have length more than 4 and remember None values are ignored in comparison.
✗ Incorrect
'elephant' (8) and 'tiger' (5) have length > 4. 'lion' (4) does not. 'dog' (3), 'cat' (3), and None (NaN, False in comparison) do not. Count is 2.
❓ visualization
advanced2:00remaining
Plot string length distribution
You have a pandas Series of strings. Which code snippet correctly plots a histogram of string lengths?
Pandas
import pandas as pd import matplotlib.pyplot as plt s = pd.Series(['red', 'blue', 'green', 'yellow', 'purple', 'orange']) # Fill in the missing code to plot histogram of string lengths
Attempts:
2 left
💡 Hint
Use the pandas string accessor to get lengths before plotting.
✗ Incorrect
s.str.len() returns a Series of string lengths. plt.hist() can plot this numeric data. Other options are invalid because len() is not a pandas method or attribute.
🔧 Debug
advanced1:30remaining
Identify the error in string length calculation
What error will the following code raise?
Pandas
import pandas as pd s = pd.Series(['a', 'bb', 'ccc']) lengths = s.len() print(lengths)
Attempts:
2 left
💡 Hint
Check if 'len' is a direct method of Series or accessed differently.
✗ Incorrect
The Series object does not have a 'len()' method. The correct way is to use s.str.len() to get string lengths.
🚀 Application
expert2:30remaining
Filter DataFrame rows by string length in a column
Given a DataFrame df with a column 'Name', which code correctly filters rows where the 'Name' length is exactly 5 characters?
Pandas
import pandas as pd df = pd.DataFrame({'Name': ['Alice', 'Bob', 'Charlie', 'David', 'Eve']}) # Fill in the code to filter rows with Name length 5
Attempts:
2 left
💡 Hint
Use the pandas string accessor for vectorized string length operations.
✗ Incorrect
Option B uses the correct pandas string accessor str.len() to get lengths. Option B works but is slower because it uses apply with Python len. Options B and D are invalid methods.