Python天天美味(2) - 字符遍历的艺术(转)
2013-05-07 13:36
253 查看
通常我们要遍历一个字符串中的每个字符,都要先获取字符串的长度,然后用一个For循环把每个字符取出,进行处理。但是,又是我们的Python,为我们提供了很多便捷的方式去遍历一个字符串中的字符。比如,将一个字符串转换为一个字符数组:
theList = list(theString)
同时,我们可以方便的通过for语句进行遍历:
for c in theString:
do_something_with(c)
甚者,使用这样的语句:
result = [do_something_with(c) for c in theString if c == 'x']
同时,还可以使用map语句,下面,我们开始上菜吧!传说中有一个神奇的字符串,被病毒感染了,被病毒附上了许多x字符,你将设计一个引擎,把病毒x出去,把我们神奇的字符串输出来。程序如下:
theString = 'Ix lixkxex xpxytxhxonx !'
def PrintEngine(c):
if c != 'x':
print c,
map(PrintEngine, theString)
输出结果:
I like python !
theList = list(theString)
同时,我们可以方便的通过for语句进行遍历:
for c in theString:
do_something_with(c)
甚者,使用这样的语句:
result = [do_something_with(c) for c in theString if c == 'x']
同时,还可以使用map语句,下面,我们开始上菜吧!传说中有一个神奇的字符串,被病毒感染了,被病毒附上了许多x字符,你将设计一个引擎,把病毒x出去,把我们神奇的字符串输出来。程序如下:
theString = 'Ix lixkxex xpxytxhxonx !'
def PrintEngine(c):
if c != 'x':
print c,
map(PrintEngine, theString)
输出结果:
I like python !
相关文章推荐
- Python天天美味(2) - 字符遍历的艺术
- Python天天美味(3) - 字符转换(转)
- Python天天美味(23) - enumerate遍历数组
- Python天天美味(8) - 字符串中的字符倒转(转)
- Python天天美味(3) - 字符转换
- Python字符遍历的艺术
- Python字符遍历的艺术
- Python天天美味(8) - 字符串中的字符倒转
- Python天天美味(32) - python数据结构与算法之堆排序
- Python天天美味(21) - httplib,smtplib
- Python 天天美味(37) - 让python的unittest像gtest一样输出
- python天天进步(2)--文件操作之遍历目录
- 【python】字符遍历
- Python天天美味(1) - 交换变量(转)
- Python天天美味(11) - 可爱的大小写(转)
- python天天进步(3)--文件操作之遍历目录
- Python天天美味(10) - 除法小技巧
- Python天天美味(22) - 拷贝对象(深拷贝deepcopy与浅拷贝copy)
- Python天天美味(6) - strip lstrip rstrip(转)
- Python天天美味(33) - 五分钟理解元类(Metaclasses)[转]