【发布时间】:2019-12-21 05:22:08
【问题描述】:
对于给定的字符串,我只需要将单词的字符与一定数量的兄弟姐妹组合,即Hello 与 3,组合将是:Hel、ell、llo。
a 正在尝试使用组合和排列函数,但我无法控制该函数如何组合字符。
【问题讨论】:
-
您应该包含您尝试过的内容
标签: python python-3.x string permutation permute
对于给定的字符串,我只需要将单词的字符与一定数量的兄弟姐妹组合,即Hello 与 3,组合将是:Hel、ell、llo。
a 正在尝试使用组合和排列函数,但我无法控制该函数如何组合字符。
【问题讨论】:
标签: python python-3.x string permutation permute
>>> 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)) []
【讨论】:
您可以遍历字符串索引并忽略最后几个长度太短的索引
>>> foo = 'hello'
>>> [foo[i:i+3] for i, _ in enumerate(foo) if i+2 < len(foo)]
['hel', 'ell', 'llo']
【讨论】: