You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现字符串全右旋转?我的Python代码为何输出重复结果?

问题分析与修正

你的代码有两个核心问题,导致输出全是原字符串:

1. 切片拼接逻辑完全错误

你写的word[0 : length-n] + word[length-n:],本质是把字符串从length-n的位置切成两段再拼回去——这和原字符串完全一样,相当于做了无用功。

右旋转1位的正确逻辑应该是把字符串最后n个字符移到最前面,剩下的字符跟在后面。比如右旋转1位时,正确的切片是word[-n:] + word[:-n](word[-1:]取最后1个字符,word[:-1]取除了最后1个之外的所有字符)。

2. 循环中没有更新旋转状态

你每次循环都用初始的word和固定的n=1计算,自然每次结果都一样。要实现逐次旋转,要么每次基于上一次的旋转结果继续操作,要么根据循环的索引计算当前的偏移量。

修正后的代码

这里提供两种实现方式:

方式一:基于上一次结果迭代旋转

word = "Abobus"
length = len(word)
n = 1

def rotation():
    current_word = word
    print(current_word)  # 先输出原字符串
    for _ in range(length):  # 循环length次,得到length种旋转结果,最后回到原字符串
        current_word = current_word[-n:] + current_word[:-n]
        print(current_word)

rotation()

方式二:通过索引计算偏移量(不修改原字符串)

word = "Abobus"
length = len(word)

def rotation():
    for i in range(length + 1):
        # 每次右旋转i位,取最后i个字符移到前面
        rotated = word[-i:] + word[:-i] if i !=0 else word
        print(rotated)

rotation()

两种方式都能输出你期望的结果:

Abobus
sAbobu
usAbob
busAbo
obusAb
bobusA
Abobus

内容的提问来源于stack exchange,提问作者RegularClique

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 23:25:59