文本处理 - 每次一个字符
为了对字符串中的每个字符处理可以采用下面几种方法:
1. 使用内建函数list将字符串转换成列表,列表的每一项是字符串中字符
1 thelist = list(TheString)
2. 使用for循环直接遍历字符串中的每个字符
for c in theString: do_something_with(c)
3. 使用列表推倒
1 result = [do_something_with(c) for c in theString]
4. 使用map
1 result = map(do_something_with, thesting)
代码测试:
1 #!/usr/bin/env python
2
3 import sys
4 import string
5
6 def print_string(thelist):
7 for c in thelist:
8 sys.stdout.write(c)
9 sys.stdout.write('\n')
10
11 def passwd_encrypt(c):
12 alphabet = string.ascii_letters
13 index = alphabet.find(c)
14 index = (index + 4) % 36
15 return alphabet[index]
16
17 if __name__ == '__main__':
18 passwd = 'uzero'
19 print 'password: %s' % passwd
20 sys.stdout.write('list comprehensions: ')
21 result = [passwd_encrypt(c) for c in passwd]
22 print_string(result)
23 sys.stdout.write('map: ')
24 result = map(passwd_encrypt, passwd)
25 print_string(result)
求两个字符串的交集或者并集,可以先将字符串转换为集合,然后使用集合功能求交集:
1 #!/usr/bin/env python 2 3 import sys 4 5 magic_chars = set('uzero') 6 poppings_chars = set('Uzero') 7 8 sys.stdout.write('intersect: %s\n' % ''.join(magic_chars & poppings_chars)) 9 sys.stdout.write('unite: %s' % ''.join(magic_chars | poppings_chars))
原书使用sets模块,python2.6以后不建议使用该模块,否则运行python代码时会打出:DeprecationWarning: the sets module is deprecated.现在sets模块已经被内建的set,frozenset类型代替