首页 文章资讯内容详情

在 Python 中将大小为 n 的字符串向左旋转 n 次的程序

2026-06-03 2 花语

假设我们有一个大小为n的字符串s。我们必须通过将它们旋转1个位置、2个位置...n个位置来找到所有旋转的字符串。

因此,如果输入类似于s="hello",那么输出将是[elloh,llohe,lohel,ohell,hello]

示例

让我们看看以下实现以获得更好的理解-

def solve(s): res = [] n = len(s) for i in range(0, n): s = s[1:n]+s[0] res.append(s) return res s = "hello" print(solve(s))

输入

hello输出结果[elloh, llohe, lohel, ohell, hello]