Python – Get K length substrings of a string

Python – Get K length substrings of a given string

To get the substrings of a given String of a specific length in Python, iterate over the string across the length of the string for the specific length substrings.

Programs

In the following program, we read a string from user using input() function, and then find all the substrings of specified length.

1. Get substrings of specific length in a string using For Loop

In the following program, we define a function getKLengthSubStrings() that takes a string, and length of required substrings as parameters. The function returns a list, with all the substrings of given string, with the specified length. We use a For Loop to traverse from starting to end of the string, and find k-length strings.

We shall take an input string in x, and length of substrings in k, and then find the substrings by calling getKLengthSubStrings() function.

Python Program

def getKLengthSubStrings(x, k):
    allSubStrings = []

    for i in range(0, len(x) - k + 1):
        allSubStrings.append(x[i:i+k])

    return allSubStrings

# Take an input string
x = 'apple'

# Take a length of substrings
k = 3

# Find all the substrings with specific length
result = getKLengthSubStrings(x, k)
print(result)
Run Code Copy

Output

apple
3
['app', 'ppl', 'ple']

Reference tutorials for the above program

Summary

In this Python Tutorial, we learned how to find all the possible substrings of specified length in a given string.

Related Tutorials

Code copied to clipboard successfully 👍