Python格式化输出,指定宽度格式化

import re

text = """
0    10   200    300 -1
10   200  3000    3  -2
100  9    8     500  -3
"""
#居左格式化:语法如下
fmt = u"{:<4},\t{:<4},\t{:<4},\t{:<4},\t{:<4}"
print("居左格式化:")
for e in text.split("\n")[1:-1]:
    m = re.search("\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)", e)
    o = "{" + fmt.format(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5)) + "},"
    print(o)

#居中格式化:语法如下
fmt = u"{:^4},\t{:^4},\t{:^4},\t{:^4},\t{:^4}"
print("居中格式化:")
for e in text.split("\n")[1:-1]:
    m = re.search("\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)", e)
    o = "{" + fmt.format(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5)) + "},"
    print(o)

#居右格式化:语法如下
fmt = u"{:^4},\t{:>4},\t{:>4},\t{:>4},\t{:>4}"
print("居右格式化:")
for e in text.split("\n")[1:-1]:
    m = re.search("\s*(\d+)\s+(\d+)\s+(\d+)\s+(\d+)\s+(-?\d+)", e)
    o = "{" + fmt.format(m.group(1), m.group(2), m.group(3), m.group(4), m.group(5)) + "},"
    print(o)

#打印对比结果如下:
在这里插入图片描述
#格式化打印日期:格式2021-06-20 21:06:01

import time
fmt = u"{}-{}-{} {}:{}:{}"
date = time.localtime(time.time())
year = str(date.tm_year).zfill(4)
mon  = str(date.tm_mon).zfill(2)
day  = str(date.tm_mday).zfill(2)
hour = str(date.tm_hour).zfill(2)
min  = str(date.tm_min).zfill(2)
sec  = str(date.tm_sec).zfill(2)
date_time = fmt.format(year, mon, day, hour, min, sec)
print(date_time)

打印结果: 2021-06-20 21:19:31

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值