通过使用与[start:end:step]表示法相同的字段来调用slice来创建slice:
sl = slice(0,4)
要使用切片,只需将其作为索引传递到列表或字符串中即可:
>>> s = "ABCDEFGHIJKL">>> sl = slice(0,4)>>> print(s[sl])'ABCD'
假设您有一个固定长度的文本字段文件。您可以定义切片列表,以轻松地从该文件中的每个“记录”中提取值。
data = """010GEORGE JETSON 12345 SPACESHIP ST HOUSTON TX0020WILE E COYOTE 312 ACME BLVD TUCSON AZ0030FRED FLINTSTONE 246 GRANITE LANE BEDROCK CA0040JonNY QUEST 31416 SCIENCE AVE PALO ALTO CA""".splitlines()fieldslices = [slice(*fielddef) for fielddef in [ (0,4), (4, 21), (21,42), (42,56), (56,58), ]]fields = "id name address city state".split()for rec in data: for field,sl in zip(fields, fieldslices): print("{} : {}".format(field, rec[sl])) print('')
印刷品:
id : 0010name : GEORGE JETSON address : 12345 SPACESHIP ST city : HOUSTON state : TXid : 0020name : WILE E COYOTE address : 312 ACME BLVD city : TUCSON state : AZid : 0030name : FRED FLINTSTONE address : 246 GRANITE LANE city : BEDROCK state : CAid : 0040name : JonNY QUEST address : 31416 SCIENCE AVE city : PALO ALTO state : CA
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)