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

字符串按指定长度分块反转后拼接的自动化实现问题

字符串分块反转自动化实现方案

我正在完成一项技术挑战,需要将字符串按指定数值分割为若干块,反转每个块后重新拼接。目前已经实现了手动处理的代码,但无法完成该任务的自动化,手动代码如下:

def switch (n, txt):
    a = (txt [0:n] [::-1]) #here I devide and reverse the txt
    b = (txt [n:2*n] [::-1])
    c = (txt [2*n : 3*n] [::-1])
    d = (txt [3*n : 4*n] [::-1])
    e = (txt [4*n : 5*n] [::-1])
    f = (txt [5*n : 6*n] [::-1])
    g = (txt [6*n : 7*n] [::-1])
    h = (txt [7*n : 8*n] [::-1])
    ch = (txt [8*n : 9*n] [::-1])
    i = (txt [9*n : 10*n] [::-1])
    j = (txt [10*n : 11*n] [::-1])
    k = (txt [11*n : 12*n] [::-1])
    l = (txt [12*n : 13*n] [::-1])
    m = (txt [13*n : 14*n] [::-1])

    return (a + b + c + d + e + f + g + h + ch + i + j + k + l + m ) #and here I glue it back together

print (switch (3, "Potatos are veges")) #The result should be "topotaa s ergevse"

自动化实现方案

手动代码的问题在于硬编码了固定数量的块变量,只能处理长度有限的字符串,无法适配任意长度的输入。可以通过循环或生成器实现完全自动化:

基础循环版本

def switch(n, txt):
    result = ""
    # 按步长n遍历所有块的起始索引
    for i in range(0, len(txt), n):
        # 截取当前块并反转后拼接到结果
        chunk = txt[i:i+n]
        result += chunk[::-1]
    return result

print(switch(3, "Potatos are veges"))  # 输出: topotaa s ergevse

简洁生成器版本

用join方法直接拼接所有反转后的块,代码更简洁高效:

def switch(n, txt):
    return ''.join(txt[i:i+n][::-1] for i in range(0, len(txt), n))

代码说明

  • range(0, len(txt), n) 生成从0开始、步长为n的索引序列,覆盖字符串的所有块起始位置
  • txt[i:i+n] 自动处理最后一个长度不足n的块,直接截取到字符串末尾
  • 每个块通过[::-1]反转后,直接拼接到结果中,无需手动定义大量变量

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 16:25:21