文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- Zoom.Quiet [2004-08-11 17:31:51]

1. 每次处理字符串的一个字符

3.2 Processing a String One Character at a Time

每次处理字符串的一个字符

Credit: Luther Blissett

1.1. 问题 Problem

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

你想每次处理字符串的一个字符

1.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):

你能使用带有string的list作为它的参数去构建一个字符的list(也就是说,每个字符串的长度为 一)

thelist = list(thestring)

You can loop over the string in a for statement:

你能使用一个for语句在string上做循环:

   1 for c in thestring:
   2     do_something_with(c)

You can apply a function to each character with map:

你能在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.

这是同loop相同的。但是它处理在string里的每个字符作为它的参数的do_something_with函数的结果的list。

1.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). 在python,

字符仅仅是长度为一的字符串。你能在string上做循环一个接一个的去访问它的每个字符。你能为 相同的目的去使用map,你需要做的是为每个字符调用一个函数。总之,你能调用内建的类型 list 取得string的长度为一的子字符串(也就是说,sting的字符)

1.4. 参考 See Also

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