python限制输出宽度_python中怎么限制每行的字符数,调整每行为指定的字符数输出...

修改一下

step = 100

f = open('r.txt','w')

ls = open('a.txt','r').readlines()

header = ''

content = ''

ls.append('#####\n') # add mark of file end

for row, l in enumerate(ls):

if l.startswith('#'): # encounter new header

if content != '':

f.write(header) # write header

for i in range((len(content) - 1) / step + 1): # zip content

f.write(content[i*step : i*step + step] + '\n') # write content

content = '' # reset content

header = ('\n' if row > 0 else '') + l # write header

else:

content += l.replace('\n','') # add new line to content

在 PrettyTable ,可以使用 `max_width` 参限制每个单元格的最大宽度,从而限制每行字符。例如: ``` from prettytable import PrettyTable x = PrettyTable() x.field_names = ["City name", "Area", "Population", "Annual Rainfall"] x.add_row(["Adelaide", 1295, "1158259 (2006)", 600.5]) x.add_row(["Brisbane", "5905 (2011)", 1857594, 1146.4]) x.add_row(["Darwin", 112, 120900, 1714.7]) x.add_row(["Hobart", 1357, 205556, 619.5]) x.add_row(["Sydney", 2058, 4336374, 1214.8]) x.add_row(["Melbourne", 1566, 3806092, 646.9]) x.add_row(["Perth", 5386, 1554769, 869.4]) x.align["City name"] = "l" x.align["Area"] = "r" x.align["Population"] = "r" x.align["Annual Rainfall"] = "r" x.max_width["City name"] = 15 x.max_width["Area"] = 15 x.max_width["Population"] = 20 x.max_width["Annual Rainfall"] = 15 print(x) ``` 输出: ``` +---------------+---------------+----------------------+-----------------+ | City name | Area| Population | Annual Rainfall | +---------------+---------------+----------------------+-----------------+ | Adelaide | 1295| 1158259 (2006) | 600.5 | | Brisbane | 5905 (2011)| 1857594 | 1146.4 | | Darwin | 112| 120900 | 1714.7 | | Hobart | 1357| 205556 | 619.5 | | Sydney | 2058| 4336374 | 1214.8 | | Melbourne | 1566| 3806092 | 646.9 | | Perth | 5386| 1554769 | 869.4 | +---------------+---------------+----------------------+-----------------+ ``` 可以看到,每个单元格的最大宽度限制为了指定的长度,从而限制每行字符
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值