Library contents

Python List comprehension with str.strip

Transform every badge name into a clean string in a new list.

A simple example

List comprehension with str.strip

  1. Start with " A ", " B "
  2. Do this Trim each element
  3. Result "A", "B"
Applying the same text operation to each element preserves the list order.

Syntax

Python syntax
[name.strip() for name in names]
Run these examples in Python

Save one example at a time as lesson.py. Use Python 3.9 or later.

python3 lesson.py

Clean the names on two visitor badges

A reception desk receives visitor names copied from an email. Extra spaces at the edges would make the printed badges look uneven, so the desk cleans each name while preserving arrival order.

From the programnames = [" Mira ", " Sam"]
ResultMira, Sam
lesson.py
names = [" Mira ", " Sam"]
badges = [name.strip() for name in names]
print(", ".join(badges))
Output
Mira, Sam

The new list keeps arrival order with the extra spaces removed.

Advertisements

Clean a volunteer roster

Two names pasted from a form have stray spaces. The printer trims surrounding spaces from each label. Which names remain on the badge sheet?

Given“ Isa” · “Lou ”
Worked resultIsa · Lou

Prepare two exhibit labels

A curator copies padded names out of a spreadsheet. The printer trims surrounding spaces from each label. Which names remain on the badge sheet?

Given“ Clay ” · “ Ink”
Worked resultClay · Ink

What to watch for

Keep the return value because strip creates a new string.

Documentation for List comprehension with str.strip