[Tutor] Iterating over a list for a certain character...

Kalle Svensson kalle@gnupung.net
Fri, 14 Dec 2001 12:50:31 +0100


[Brett Kelly]
> ok, i have read a file into a list of strings, and i need to copy out all of
> the strings that contain a certain character, sort them, and print them.

To read a file to a list of strings, check out the readlines and xreadlines
methods of file objects.
http://www.python.org/doc/current/lib/bltin-file-objects.html

To see if a character is in a string, use the in statement:

>>> "r" in "bar"
1
>>> "r" in "foo"
0

If you want to check for more complex things than characters, like strings or
regular expressions, check out string methods (especially find) and the re
module.
http://www.python.org/doc/current/lib/string-methods.html
http://www.python.org/doc/current/lib/module-re.html

Sorting is done with the list method sort.  More info:
http://www.python.org/doc/current/lib/typesseq-mutable.html

Looping can be done with for loops or, quite elegantly, with list
comprehensions:

>>> words = ["omph", "foo", "fum"]
>>> matches = [w for w in words if "o" in w]
>>> matches
['omph', 'foo']
>>> matches.sort()
>>> matches
['foo', 'omph']

Peace,
  Kalle
-- 
Kalle Svensson (kalle@gnupung.net) - Laziness, impatience, hubris: Pick two!
English: http://www.gnupung.net/  Svenska: http://www.lysator.liu.se/~kalle/
Stuff: ["http://www.%s.org/" % x for x in "gnu debian python emacs".split()]