Ad

How To Get All Sub-string On A String (User Input)

- 1 answer

Code

def substring(word,f,l):
    word_length = len(word)
    l1 = str(word.index(f))
    l2 = str(word.index(l))
    a = word[int(l1):int(l2)+1]
    sub_list = []
    for i in l1:
        for j in l2:
            sub_list.append(a)
    return sub_list

w1 = input("Enter String: ")
w2 = input("Enter start: ")
w3 = input("Enter end: ")
print(substring(w1,w2,w3))

Input

python programming # string
p                  # start
g                  # end

Output

['python prog', 'python prog']

Expected Output

['python prog', 'prog', 'programming']

What should I do to get all the substrings on a string base on the user input?

Ad

Answer

def substring(line, start, end):
    for i in (start, end):
        if i not in line:
            raise Exception(f"`{i}` not found in `{line}`!")
    start_indexes, end_indexes, sub_list = [], [], []
    line_length, end_length = len(line), len(end)
    for i in range(len(line)):
        if line[i:].startswith(start):
            start_indexes.append(i)
        elif line[i:].startswith(end):
            end_indexes.append(i)
    for i in start_indexes:
        for j in end_indexes:
            right = j + end_length
            if i < right and right-i < line_length:
                sub_list.append(line[i : right])
    return sub_list

Output:

['python prog', 'prog', 'programming']
Ad
source: stackoverflow.com
Ad