Python 3 日记(二)
2012-12-10 星期一
1.控制大小写和访问子字符串1)控制大小写
# 封装成函数print('**************************************************************')def fields(base_format, the_line, last_field = False): num_remain = len(the_line) - struct.calcsize(base_format) the_format = '%s %d%s' % (base_format, num_remain, last_field and 's' or 'x') return struct.unpack(the_format, the_line)print(fields(base_format, the_line, False))print(fields(base_format, the_line, True))# 使用memorizing机制的fields版本# 适用于在循环内部调用print('**************************************************************')def fields_mem(base_format, the_line, last_field = False, _cache = {}): key = base_format, len(the_line), last_field the_format = _cache.get(key) if the_format is None: num_remain = len(the_line) - struct.calcsize(base_format) _cache[key] = the_format = '%s %d%s' % ( base_format, num_remain, last_field and 's' or 'x') return struct.unpack(the_format, the_line)print(fields(base_format, the_line, False))print(fields(base_format, the_line, True))# 对按字符个数分隔的方法的封装def split_by(the_line, n, last_field = False): pieces = [the_line[k: k+n] for k in range(0, len(the_line), n)] if not last_field and len(pieces[-1]) < n: pieces.pop() return piecesprint(split_by(the_line, 5, False))print(split_by(the_line, 5, True))# 将数据切成指定的列的封装def split_at(the_line, cuts, last_field = False): pieces = [ the_line[i:j] for i, j in zip([0] + cuts, cuts + [None]) ] if not last_field: pieces.pop() return piecesprint(split_at(the_line, cuts, False))print(split_at(the_line, cuts, True))# 用生成器来实现print('**************************************************************')def split_at_yield(the_line, cuts, last_field = False): last = 0 for cut in cuts: yield the_line[last: cut] last = cut if last_field: yield the_line[last: ] print(split_at_yield(the_line, cuts, False))print(split_at_yield(the_line, cuts, True)) def split_by_yield(the_line, n, last_field = False): return split_at_yield(the_line, range(n, len(the_line), n), last_field)print(list(split_by_yield(the_line, 5, False)))print(list(split_by_yield(the_line, 5, True)))输出:
**************************************************************
(b'hello ', b'python ', b'hello ')
(b'hello ', b'python ', b'hello ', b'world!')
**************************************************************
(b'hello ', b'python ', b'hello ')
(b'hello ', b'python ', b'hello ', b'world!')
[b'hello', b' keya', b'n pyt', b'hon h', b'i hel', b'lo wo']
[b'hello', b' keya', b'n pyt', b'hon h', b'i hel', b'lo wo', b'rld!']
[b'hello ', b'keyan ', b'python ', b'hi ', b'hello ']
[b'hello ', b'keyan ', b'python ', b'hi ', b'hello ', b'world!']
**************************************************************
[b'hello ', b'keyan ', b'python ', b'hi ', b'hello ']
[b'hello ', b'keyan ', b'python ', b'hi ', b'hello ', b'world!']
[b'hello', b' keya', b'n pyt', b'hon h', b'i hel', b'lo wo']
[b'hello', b' keya', b'n pyt', b'hon h', b'i hel', b'lo wo', b'rld!']