Python Cookbook 2Nd Edition Jun 1002005 [Electronic resources]

David Ascher, Alex Martelli, Anna Ravenscroft

نسخه متنی -صفحه : 394/ 18
نمايش فراداده

Recipe 1.1. Processing a String One Character at a Time

Credit: Luther Blissett

Problem

You want to process a string one character at a time.

Solution

You can build a list whose items are the string's characters (meaning that the items are strings, each of length of onePython doesn't have a special type for "characters" as distinct from strings). Just call the built-in list, with the string as its argument:

thelist = list(thestring)

You may not even need to build the list, since you can loop directly on the string with a for statement:

for c in thestring:
do_something_with(c)

or in the for clause of a list comprehension:

results = [do_something_with(c) for c in thestring]

or, with exactly the same effects as this list comprehension, you can call a function on each character with the map built-in function:

results = map(do_something, thestring)

Discussion

In Python, characters are just strings of length one. You can loop over a string to access each of its characters, one by one. You can use map for much the same purpose, as long as what you need to do with each character is call a function on it. Finally, you can call the built-in type list to obtain a list of the length-one substrings of the string (i.e., the string's characters). If what you want is a set whose elements are the string's characters, you can call sets.Set with the string as the argument (in Python 2.4, you can also call the built-in set in just the same way):

import sets
magic_chars = sets.Set('abracadabra')
poppins_chars = sets.Set('supercalifragilisticexpialidocious')
print ''.join(magic_chars & poppins_chars)   # set intersection
acrd

See Also

The Library Reference section on sequences; Perl Cookbook Recipe 1.5.