# Find all possible substrings after deleting k characters in Python

we are given a string. The required task is to take out one letter from the string and print the remaining letters in the string. And this we have to so for each letter of the string.

## With loops and range

This is a basic programming approach in which we first list out the parameters required like declare the string, create variables for start and end positions and create a temporary placeholder for each of the letters. The we create a function that will iterate through each of the letters and create a string of remaining letters.

## Example

Live Demo

list = []

def letterCombinations(s, t, start, end, index, k):
if (index == k):
elem = ''

for j in range(k):
elem += t[j]
list.append(elem)
return

i = start
while (i <= end and end - i + 1 >= k - index):
temp[index] = s[i]
letterCombinations(s, t, i + 1,
end, index + 1, k)
i += 1
stringA = 'Apple'
k = 1
temp = [0] * (len(stringA) - k)
start = 0
end = len(stringA) - 1

letterCombinations(stringA, temp, start, end, 0, len(stringA) - k)
print(set(list))

## Output

Running the above code gives us the following result −

{'pple', 'Aple', 'Appl', 'Appe'}

## with itertools

In this approach we use the module itertools which has a function named combinations. That takes care of creating all possible combinations of letters after we remove one letter from the given string.

## Example

from itertools import combinations

stringA = 'Apple'
k = 1

# using combinations
res = set([''.join(i) for i in combinations(stringA, len(stringA) - k)])

print(res)

## Output

Running the above code gives us the following result −

{'Appl', 'Aple', 'Appe', 'pple'}

Updated on: 26-Aug-2020

131 Views