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
- Start with " A ", " B "
- Do this Trim each element
- Result "A", "B"
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.pyClean 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.
names = [" Mira ", " Sam"]
badges = [name.strip() for name in names]
print(", ".join(badges))
Mira, Sam
The new list keeps arrival order with the extra spaces removed.
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?
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?
What to watch for
Keep the return value because strip creates a new string.