编写一个带有 2 个参数(字符串和整数)的函数,它应该像我在描述字段中写的那样打印出一个正方形字符

Write a function with 2 arguments (string and integer) and it should print out a square of characters as I wrote in description field

这是我的功能,但它不能正常工作。第一行输出很好,但第二行从头开始而不是继续它。 :

def squared(text, length):
    for i in range(length):
        if i%length==0: 
            result=text*length
        
        print(result[0:length])
        
if __name__ == "__main__":
    squared("abc", 5)

输出必须是:

abcab
cabca
bcabc
abcab
cabca

您可以 cycle 围绕文本和每行 islice 接下来的 5 行。这样您就不必管理任何索引和 mod 数学。

from itertools import cycle, islice

def squared(text, length):
    letters = cycle(text)  # lazy iterator -> abcabcabcabc....
    for i in range(length):
        print("".join(islice(letters, length)))
        # print(*islice(letters, length), sep="")

>>> squared("abc", 5)
abcab
cabca
bcabc
abcab
cabca

一些文档