Python Cookbook学习记录 ch1_1_2013/10/20

1.1 每次处理一个字符

a. list方法将字符串转成列表

>>> thestring = 'Helloworld'
>>> thelist = list(thestring)
>>> print thelist
['H', 'e', 'l', 'l', 'o', 'w', 'o', 'r', 'l', 'd']

b.使用for循环完成字符串遍历

>>> thestring = 'Helloworld'
>>> thelist = []
>>> for item in thestring:
      thelist += item.upper()    
>>> print thelist
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

c.使用列表推导方法

>>> thestring = 'Helloworld'
>>> thelist = [item.upper() for item in thestring]
>>> print thelist
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']

d.使用map函数
在map里面直接使用upper函数会报错,提示没有upper方法,使用自己的定义的函数没有问题

>>> thestring = 'Helloworld'
>>> def charupper(x):
      return x.upper()

>>> thelist = map(charupper,thestring)
>>> print thelist
['H', 'E', 'L', 'L', 'O', 'W', 'O', 'R', 'L', 'D']


讨论中提到如果希望得到字符的集合,可以使用sets.Set方法,在这里复制一下代码

 获取两个字符串的交集,得到的还是字符串

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

>>> 
acrd

posted on 2013-10-20 15:44  七海之风  阅读(138)  评论(0)    收藏  举报

导航