Python天天美味(2) 字符遍历的艺术

    通常我们要遍历一个字符串中的每个字符,都要先获取字符串的长度,然后用一个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 !

Python 天天美味系列(总)

Python 天天美味(1) - 交换变量

Python 天天美味(2) - 字符遍历的艺术  

Python 天天美味(3) - 字符转换  

Python 天天美味(4) - isinstance判断对象类型 

Python 天天美味(5) - ljust rjust center

...

原文地址:https://www.cnblogs.com/coderzh/p/1177677.html