
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python – N sized substrings with K distinct characters
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.
- Related Articles
- Python program to find N-sized substrings with K distinct characters
- Count number of substrings with exactly k distinct characters in C++
- Find K-Length Substrings With No Repeated Characters in Python
- Find distinct characters in distinct substrings of a string
- Find all possible substrings after deleting k characters in Python
- Program to find maximum number of K-sized groups with distinct type items are possible in Python
- Longest Substring with At Most K Distinct Characters in C++
- Program to find length of longest substring which contains k distinct characters in Python
- Python – Sort Matrix by K Sized Subarray Maximum Sum
- Distinct Echo Substrings in C++
- Smallest Subsequence of Distinct Characters in Python
- Maximum count of substrings of length K consisting of same characters in C++
- Find N distinct numbers whose bitwise Or is equal to K in Python
- Find all distinct pairs with difference equal to k in Python
- Program to count number of distinct substrings in s in Python

Advertisements