2007-06-12

 

Python Cook 1.1 处理字符串中的字符

需求:

要一个一个的处理字符串中的字符。

讨论:

    在python中,字符串是不可变的字符的序列。所以,可以像操作普通的序列一样,按照下标来处理字符。如果要依次处理所有的字符,写一个for循环是效率比较高的方法。
如:
for c in thestring:
    do_sth(c)

更快捷的方法:
result = [do_sth(c) for c in thestring]

使用build-in的map方法:
result = map(do_sth,thestring)

例子:

把一个字符串中的所有字符的ascii码按序列输出.

thestring = 'this is a test'
for c in thestring:
    print ord(c),

print [ord(c) for c in thestring]

print map(ord,thestring)

输出的结果如下:

116 104 105 115 32 105 115 32 97 32 116 101 115 116
[116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116]
[116, 104, 105, 115, 32, 105, 115, 32, 97, 32, 116, 101, 115, 116]

需要注意的上面的第三种写法,map的第一个参数是一个方法名,不带参数,且这个方法必须是callable的.
python中对callable的解释是:

callable(...)
    callable(object) -> bool
   
    Return whether the object is callable ( i.e., some kind of function).
    Note that classes are callable, as are instances with a __call__() method.

标签:


Comments: 发表评论



<< Home

This page is powered by Blogger. Isn't yours?