python字符串末尾添加字符边框_为矩形字符矩阵添加边框(*)

在Python中,由于字符串的不可变性,直接编辑字符串中的字符是不被允许的。本文介绍如何为矩形字符矩阵添加边框。提供两种方法,一种简单适用于整齐的文本,另一种更复杂的方法能处理不规则的文本。通过循环和字符串格式化,可以在字符串两侧添加星号作为边框。
摘要由CSDN通过智能技术生成

字符串是不可变的,因此您不能“编辑”其中的单个字符,而不是将其编入索引中—这就是您在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了解错误发生的原因-我留下了文本,这样他的文章就不会丢失引用。在

521f7b4ecb07f0775b007b97aed97953.png

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值