def my_method(my_str):
# split the string as desired
segments = my_str.split('AAAA')
# make an empty output list to add things to
output = []
# iterate through all segments except the last
for idx in range(len(segments) - 1):
# take the last three characters of each segment,
# and the first three characters of the next segment,
# and add them to output
output = output + [segments[idx][-3:], segments[idx + 1][:3]]
return output
print(my_method('acbgfhtyesdktAAAAkghtruejdsdyhuiAAAAncgdsdgtef'))
# ['dkt', 'kgh', 'hui', 'ncg']
我更喜欢的解决方案是使用regex,然后将其展平:
import re
def my_method2(my_str):
return [e for s in re.findall(r'(...)AAAA(...)', my_str) for e in s]
print(my_method2('acbgfhtyesdktAAAAkghtruejdsdyhuiAAAAncgdsdgtef'))
# ['dkt', 'kgh', 'hui', 'ncg']
如果您必须使用
for
循环,那么您可以这样做:我更喜欢的解决方案是使用regex,然后将其展平:
相关问题 更多 >
编程相关推荐