如何使用for循环在模式前后提取特定长度的字符串

2024-09-30 05:28:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个string='acbgfhtyesdktAAAAkghtruejdsdyhuiAAAAncgdsdgtef'

我想使用for循环来提取“AAAA”前后具有特定长度的字符串

例如,我希望我的输出是['dkt', 'kgh', 'hui', 'ncg']

string.split('AAAA')

可以给我我想要的,但它没有给我3个字符长度的字符串

我需要用for循环来概括它


Tags: 字符串forstringsplitaaaa个字符ncghui
1条回答
网友
1楼 · 发布于 2024-09-30 05:28:59

如果您必须使用for循环,那么您可以这样做:

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']

相关问题 更多 >

    热门问题