访问子字符串

来源:互联网 发布:淘宝 自助服务 编辑:程序博客网 时间:2024/06/16 09:35
切片是个好方法,但是它一次只能取得一个字段;如果还考虑字段的长度,struct.unpack可能更适合。
import structdef fields(baseformat, theline, lastfield=False):    # theline超出的长度也由这个base-format确定    # (通过struct.calcsize计算确切的长度)    numremain = len(theline) - struct.calcsize(baseformat)    # 用合适的s或x字段完成格式,然后unpack    format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x")    return struct.unpack(format, theline)  

利用缓存的方法:

import structdef fields(baseformat, theline, lastfield=False, _cache={}):    # 生成键并尝试获得缓存的格式字符串    key = baseformat, len(theline), lastfield    format = _cache.get(key)    if format is None:        # 没有缓存的格式字符串,创建并缓存之        numremain = len(theline) - struct.calcsize(baseformat)        _cache[key] = format = "%s %d%s" % (baseformat, numremain, lastfield and "s" or "x")    return struct.unpack(format, theline)

0 0
原创粉丝点击