将字符串的字母与给定数量的兄弟姐妹组合起来

Combine letters of a string with a given number of siblings

对于给定的字符串,我只需要将单词的字符与一定数量的兄弟姐妹组合起来,即 Hello 和 3,组合将是:Helell, llo.

a 尝试使用组合和置换函数,但我无法控制该函数如何组合字符。

您可以遍历字符串索引并忽略最后几个长度太短的索引

>>> foo = 'hello'
>>> [foo[i:i+3] for i, _ in enumerate(foo) if i+2 < len(foo)]
['hel', 'ell', 'llo']
>>> 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))
[]