# Python – N sized substrings with K distinct characters

PythonServer Side ProgrammingProgramming

When it is required to split ‘N’ sized substrings with ‘K’ distinct characters, it is iterated over, and the ‘set’ method is used to get the different combinations.

## Example

Below is a demonstration of the same

my_string = 'Pythonisfun'
print("The string is : ")
print(my_string)

my_substring = 2
my_chars = 2
my_result = []

for idx in range(0, len(my_string) - my_substring + 1):
if (len(set(my_string[idx: idx + my_substring])) == my_chars):
my_result.append(my_string[idx: idx + my_substring])
print("The resultant string is : ")
print(my_result)

## Output

The string is :
Pythonisfun
The resultant string is :
['Py', 'yt', 'th', 'ho', 'on', 'ni', 'is', 'sf', 'fu', 'un']

## Explanation

• A string is defined and is displayed on the console.

• A substring, and the characters are defined.

• An empty list is defined.

• The string is iterated with respect to the number in substring.

• If the length of the unique characters in the string is equal to the characters, it is appended to the empty list.

• This is the result which is displayed on the console.

Published on 20-Sep-2021 08:00:17