Home > Net >  Python detect if string contains specific length substring
Python detect if string contains specific length substring

Time:10-31

I am given a string and need to find the first substring in it, according to the substring's length for example: given the string 'abaadddefggg' for length = 3 I should get the output of 'ddd' for length = 2 I should get 'aa' and so on any ideas?

CodePudding user response:

One approach in Python 3.8 using itertools.groupby combined with the walrus operator:

from itertools import groupby

string = 'abaadddefggg'

k = 3
res = next(s for _, group in groupby(string) if len(s := "".join(group)) == k)
print(res)

Output

ddd

An alternative general approach:

from itertools import groupby


def find_substring(string, k):
    for _, group in groupby(string):
        s = "".join(group)
        if len(s) == k:
            return s


res = find_substring('abaadddefggg', 3)
print(res)

CodePudding user response:

You could iterate over the strings indexes, and produce all the substrings. If any of these substrings is made up of a single character, that's the substring you're looking for:

def sequence(s, length):
    for i in range(len(s) - length):
        candidate = s[i:i length]
        if len(set(candidate)) == 1:
            return candidate
  • Related