To get all possible K length substrings of a string in Python, you can use list comprehension and slicing to iterate through each possible substring.
In this example,
str
with a value of 'Hello World'
.substrings
to store all substrings of length 3.substrings
list.str = 'Hello World'
k = 3
substrings = [str[i:j+1] for i in range(len(str)) for j in range(i, len(str)) if len(str[i:j+1]) == k]
print(f'All substrings of length {k}: {substrings}')
All substrings of length 3: ['Hel', 'ell', 'llo', 'lo ', 'o W', ' Wo', 'Wor', 'orl', 'rld']
In this tutorial, we learned How to get all the possible K length Substrings in a String in Python language with well detailed examples.