通常我们要遍历一个字符串中的每个字符,都要先获取字符串的长度,然后用一个For循环把每个字符取出,进行处理。但是,又是我们的Python,为我们提供了很多便捷的方式去遍历一个字符串中的字符。比如,将一个字符串转换为一个字符数组:
   
Python天天美味(2) - 字符遍历的艺术theList = list(theString)

    同时,我们可以方便的通过for语句进行遍历:

Python天天美味(2) - 字符遍历的艺术for c in theString:
       do_something_with(c)

     甚者,使用这样的语句:

Python天天美味(2) - 字符遍历的艺术result = [do_something_with(c) for c in theString if c == 'x']

    同时,还可以使用map语句,下面,我们开始上菜吧!传说中有一个神奇的字符串,被病毒感染了,被病毒附上了许多x字符,你将设计一个引擎,把病毒x出去,把我们神奇的字符串输出来。程序如下:

Python天天美味(2) - 字符遍历的艺术theString = 'Ix lixkxex xpxytxhxonx !'
Python天天美味(2) - 字符遍历的艺术
def PrintEngine(c):
Python天天美味(2) - 字符遍历的艺术    
if c != 'x':
Python天天美味(2) - 字符遍历的艺术        
print c,
Python天天美味(2) - 字符遍历的艺术map(PrintEngine, theString)

     输出结果:

     I like python !

Python 天天美味系列(总)

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

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

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

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

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

...

相关文章:

  • 2021-06-12
  • 2021-08-11
  • 2021-10-11
  • 2021-08-17
  • 2021-08-15
  • 2022-01-15
  • 2021-08-03
猜你喜欢
  • 2021-09-18
  • 2021-10-16
  • 2021-07-22
  • 2022-01-03
  • 2021-07-27
  • 2021-07-28
  • 2021-09-14
相关资源
相似解决方案