字符串是不可变的,因此您不能“编辑”其中的单个字符,而不是将其编入索引中—这就是您在for x ..: for y: ...循环中所尝试的。在
要保留大部分代码,可以将其更改为:def addBorder(picture):
m=len(picture) #number of rows
n=len(picture[0]) #num of columns
newpic=[['*'*(n+2)]for y in range(m+2)]
for idx,text in enumerate(picture): # get text and index here
newpic[idx+1] = '*' + text+ '*' # change text in +1 row in target list
return newpic
print(addBorder( ["abc", "ded"]))
输出:
^{pr2}$
更改更多代码:def addBorder(picture):
# slightly more compley length computation, will work for ragged text as well
maxL = max(len(x) for x in picture)
patt = "*{:
rv = []
rv.append('*'*(maxL+2)) # top border
for t in picture:
rv.append(patt.format(t)) # text + adornment
rv.append('*'*(maxL+2)) # bottom border
return rv
print(addBorder( ["abc", "defgh","i"]))
输出:['*******',
'*abc *',
'*defgh*',
'*i *',
'*******']
您的索引外错误消息有点误导性-您在列表的范围内,但您正在尝试操作字符串-我认为在这里使用'str' object does not support item assignment更合适…
编辑:请参阅Azats answer了解错误发生的原因-我留下了文本,这样他的文章就不会丢失引用。在