我有很多字符串要按以下方式处理。 对于每个字符串,需要提取位置3到15的字符,但位置9除外。
因此,对于输入“F01MBBSGB50AGFX0000000000”,输出将为“MBBSGB50AGFX”。
显而易见的方法是s[3:11] + s[12:15]
但鉴于需要处理大量数据,我需要帮助推荐的方法来实现这一目标。
答案 0 :(得分:1)
当我有这样的东西时,要提取固定的字符串位置,我喜欢使用Python切片来预定义要提取的感兴趣的字段。这可能有点过分,但它将所有字段位置和长度计数信息保存在一个易于管理的数据结构中,而不是通过代码汇总[2:10]
,[12:15]
等。
# 1 2
#123456789012345678901234
samples = """\
F01MBBSGB50AGFX0000000000
F01MBCSGB60AGFX0000000000
F01MBDSGB70AGFX0000000000""".splitlines()
# define the different slices you want to get from each line;
# can be arbitrarily many, can extend beyond the length of the
# input lines, can include 'None' to imply 0 as a start or
# end-of-string as the end
indexes = [(3,9),(10,15)]
# convert to Python slices using 'slice' builtin
slices = [slice(*idx) for idx in indexes]
# make a marker to show slices that will be pulled out
# (assumes slices don't overlap, and no Nones)
marker = ''
off = 0
for idx in sorted(indexes):
marker += ' '*(idx[0]-off) + '^'*(idx[1]-idx[0])
off = idx[1]
# extract and concat
for s in samples:
print s
print marker
print ''.join(s[slc] for slc in slices)
print
打印:
F01MBBSGB50AGFX0000000000
^^^^^^ ^^^^^
MBBSGB0AGFX
F01MBCSGB60AGFX0000000000
^^^^^^ ^^^^^
MBCSGB0AGFX
F01MBDSGB70AGFX0000000000
^^^^^^ ^^^^^
MBDSGB0AGFX
如果您愿意,还可以使用(start,length)
元组定义要提取的部分,如
fields = [(3,6), (10,5)]
然后将这些转换为切片:
slices = [slice(start,start+length) for start,length in fields]
上面所有其余的代码都是一样的。