Search code examples
pythonpython-3.xstringpermutationpermute

Combine letters of a string with a given number of siblings


With a given string I need to combine the chars of the word only with a certain number of siblings, i.e., Hello with 3, the combinations will be: Hel, ell, llo.

a was trying with the combination and permutation function, but I can't control how the function combines the chars.


Solution

  • >>> def substrings(s, length=3):
    ...     yield from (s[i:i + length] for i in range(len(s) - length + 1))
    ...
    >>>
    >>> list(substrings("Hello"))
    ['Hel', 'ell', 'llo']
    >>> list(substrings("Hello", length=2))
    ['He', 'el', 'll', 'lo']
    >>> list(substrings("Hello", length=5))
    ['Hello']
    >>> list(substrings("Hello", length=6))
    []