简体   繁体   中英

Python detect if string contains specific length substring

我得到一个字符串,需要根据子字符串的长度找到其中的第一个子字符串,例如:给定字符串 'abaadddefggg' for length = 3 我应该得到 'ddd' 的输出 for length = 2 我应该得到 ' aa' 等等有什么想法吗?

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM