在.py脚本文件中输入下面的函数。使用此函数将205676543显示为3x3的正方形。向函数添加注释(使用#)来解释它是如何工作的。在函数的开头添加一个文档字符串。

需要用到图片中所给的部分代码去进行编辑,不太清楚如何去操作,希望能帮帮忙

img

用题中代码写的话是这样:

def print_wordgrid(s,ncols=3):
    """change a string to a wordgrid """
    nrows=int(len(s)/ncols)#算出行数
    for k in range(nrows):#行数范围进行遍历
        print(" ".join(s[ncols*k:nrows*(k+1)]))#对字符串切片取每行切片起始索引于0,3,6,按长度输出。
print_wordgrid('205676543')

较为通用的写法:

def print_wordgrid(s):
    """change a string to a wordgrid
        s: the length of string s is a squared numbers
        return:a wordgrid of numbers  
    """
    rs=cs=int(len(s)**(1/2))#算出行数,列数
    for k in range(cs):
        print(' '.join(s[k*cs:(k+1)*rs]))
print_wordgrid('205676543')
print_wordgrid('2056765437891259')

如有帮助,请点采纳。

# s参数是传递的字符串,ncols是每行输出的字符数量(默认为5)
# nrows是输出字符的行数,也就是s字符串的长度 / 每行字符数量,取整
# 循环nrows行
# 每行用字符串切片取ncols个字符来输出,
如ncols是3,第1次循环k为0  ncols*k为0,ncols*(k+1)为3,就是切片取s中下标0到3(但不包含3)的字符来输出。
第2次循环k为1  ncols*k为3,ncols*(k+1)为6,就是切片取s中下标3到6(但不包含6)的字符来输出。
第3次循环k为2  ncols*k为6,ncols*(k+1)为9,就是切片取s中下标6到9(但不包含9)的字符来输出。


img

如有帮助,望采纳!谢谢!