3.2 Processing a String One Character at a Time


Credit: Luther Blissett

3.2.1 Problem

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

3.2.2 Solution

You can use list with the string as its argument to build a list of characters (i.e., strings each of length one):

thelist = list(thestring)

You can loop over the string in a for statement:

for c in thestring:     do_something_with(c)

You can apply a function to each character with map:

map(do_something_with, thestring)

This is similar to the for loop, but it produces a list of results of the function do_something_with called with each character in the string as its argument.

3.2.3 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).

3.2.4 See Also

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



Python Cookbook
Python Cookbook
ISBN: 0596007973
EAN: 2147483647
Year: 2005
Pages: 346

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net