0
0
Pandasdata~15 mins

str.len() for string length in Pandas - Mini Project: Build & Apply

Choose your learning style9 modes available
Using str.len() to Find String Lengths in a DataFrame
📖 Scenario: You work at a small bookstore. You have a list of book titles and want to find out how many letters each title has. This helps you decide how much space each title will take on the shelf labels.
🎯 Goal: Build a small program that creates a list of book titles, then uses str.len() to find the length of each title. Finally, display the lengths alongside the titles.
📋 What You'll Learn
Create a pandas DataFrame with a column named Title containing the exact book titles.
Create a variable called title_lengths that stores the length of each title using str.len().
Add a new column called Length to the DataFrame using title_lengths.
Print the DataFrame to show the book titles alongside their lengths.
💡 Why This Matters
🌍 Real World
Bookstores and libraries often need to manage book titles and labels. Knowing the length of titles helps in designing labels and organizing shelves.
💼 Career
Data analysts and data scientists use string operations like <code>str.len()</code> to clean and analyze text data in many industries, including retail and publishing.
Progress0 / 4 steps
1
Create the DataFrame with book titles
Create a pandas DataFrame called books with a column named Title containing these exact book titles: 'The Great Gatsby', '1984', 'To Kill a Mockingbird', 'Pride and Prejudice', 'Moby-Dick'.
Pandas
Need a hint?

Use pd.DataFrame with a dictionary where the key is 'Title' and the value is the list of book titles.

2
Create a variable to hold the lengths of each title
Create a variable called title_lengths that uses books['Title'].str.len() to find the length of each book title.
Pandas
Need a hint?

Use str.len() on the Title column to get the length of each string.

3
Add the lengths as a new column in the DataFrame
Add a new column to the books DataFrame called Length and set it equal to the title_lengths variable.
Pandas
Need a hint?

Assign the title_lengths Series to a new column Length in the books DataFrame.

4
Print the DataFrame with titles and their lengths
Print the books DataFrame to display the book titles alongside their lengths.
Pandas
Need a hint?

Use print(books) to show the DataFrame with the new Length column.