Divide a String Into Groups of Size k

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Solution:
    def divideString(self, s: str, k: int, fill: str) -> List[str]:
        groups = []
        for i in range(0, len(s), k):
            group = s[i:i+k]
            groups.append(group)

        last_group_length = len(groups[-1])
        while last_group_length < k:
            groups[-1] += fill
            last_group_length += 1

        return groups

In this code, the first for-loop iterates over the string, s, in steps of k and creates a substring, group, from s starting at i and ending at i+k. Each group is then appended to the list, groups.

After forming all groups, we calculate the length of the last group. If the length of the last group is less than k, we enter a while-loop where we add the fill character to the last group until its length equals k.