Python循环移位字符正方形打印函数输出异常问题求解
问题原因
你写的代码存在两个核心问题:
- 移位逻辑完全缺失:只有循环第一次执行时(i=0)才会给
result赋值,后续循环全程复用第一次的result值,每次都截取前length位打印,自然所有行内容都相同。 - 没有计算每行的起始偏移量,无法实现循环移位的效果。
修正后的代码
def squared(text, length): text_len = len(text) # 拼接足够长的循环字符串,避免索引越界 full_cycle = text * (length + text_len) for row_idx in range(length): # 计算当前行的起始偏移,匹配要求的循环移位规则 start_offset = (row_idx * (text_len - 1)) % text_len print(full_cycle[start_offset: start_offset + length]) if __name__ == "__main__": squared("abc", 5)
运行后输出完全符合要求:
abcab cabca bcabc abcab cabca
可选优化(节省内存)
如果处理的字符串和长度非常大,可以不用拼接长字符串,直接通过模运算计算每个位置的字符:
def squared(text, length): text_len = len(text) for row_idx in range(length): current_line = ''.join([ text[(char_idx + row_idx * (text_len - 1)) % text_len] for char_idx in range(length) ]) print(current_line)
内容的提问来源于stack exchange,提问作者user17135153
相关产品推荐
相关产品推荐

