[Tutor] Iterating over a list for a certain character...
Fri, 14 Dec 2001 12:50:31 +0100
> 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.
To see if a character is in a string, use the in statement:
>>> "r" in "bar"
>>> "r" in "foo"
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
Sorting is done with the list method sort. More info:
Looping can be done with for loops or, quite elegantly, with list
>>> words = ["omph", "foo", "fum"]
>>> matches = [w for w in words if "o" in w]
Kalle Svensson (firstname.lastname@example.org) - 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()]