I l@ve RuBoard Previous Section Next Section

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:

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.

    I l@ve RuBoard Previous Section Next Section