Py&禅

博客园 首页 新随笔 联系 订阅 管理
problem:
处理sting,一次一个字符

Solution:
使用list()內建函数,将字符串转换为一个包含单个字符的列表
thestring = "hello world"
thelist = list(thestring)
三种遍历的方法:
for c in thestring:
    do_something_with(c)

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

results = map(do_something, the string)

Discussion:
在python中,字符串中单个字符长度为 1
除了以上的遍历单个字符的方法,还可以使用 set 集合容器

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

>>>acrd

posted on 2010-05-30 10:00  Py&禅  阅读(244)  评论(0)    收藏  举报