Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Processing collections with the for statement


The for statement is an extremely versatile way to process every item in a collection. We do this by defining a target variable, a source of items, and a suite of statements. The for statement will iterate through the source of items, assigning each item to the target variable, and also execute the suite of statements. All of the collections in Python provide the necessary methods, which means that we can use anything as the source of items in a for statement.

Here's some sample data that we'll work with. This is part of Mike Keith's poem, Near a Raven. We'll remove the punctuation to make the text easier to work with:

>>> text = '''Poe, E.
...      Near a Raven
...
... Midnights so dreary, tired and weary.'''
>>> text = text.replace(",","").replace(".","").lower()

This will put the original text, with uppercase and lowercase and punctuation into the text variable. We used some method functions from Chapter 2, Simple Data Types...