gpt4 book ai didi

python - 格式化表 ascii python

转载 作者:太空宇宙 更新时间:2023-11-04 04:03:49 25 4
gpt4 key购买 nike

你好,我想在第二列之后添加一个空格,而不是将它添加到第一列,但是如果我试图以一种肮脏的方式添加它,比如 '| '.join 我的细胞变得一团糟,但我怎么会有输出的欲望呢?我也试过 rjust(3) 但它不起作用

_id = ['1', '2', '3','4']
transport = ['http','tcp','https','dns']
agent = ['10.10.1.1','10.10.1.2','10.10.1.3','10.10.1.4']
username = ['DESKTOP-123\\user','root','user','user']
os = ['windows/amd64','linux/amd64','windows/amd64','linux/amd64']
seen = ['2019-08-31 13:10:08','2019-08-31 13:10:08','2019-08-31 13:10:08','2019-08-31 13:10:08']
titles = ['ID', 'Transport', 'Agent', 'Username','Operating System','Last Seen']
data = [titles] + list(zip(_id, transport, agent, username,os,seen))

def os():
print("\t")
for i, d in enumerate(data):
line = '|'.join(str(x).ljust(18) for x in d)
print(line)
if i == 0:
sep = '-' * 18 + '+'
line = ''.join(sep for x in d)
print(line)
print("\t")

我想让输出在管道执行第一列之后添加一个空格

|1 | 2 | 3 |
+--+---+---+
|4 | 5 | 6 |
|7 | 8 | 9 |

最佳答案

将枚举数据里面的第一行定义替换为:

line = f'{str(d[0]).ljust(18)}| {"| ".join(str(x).ljust(17) for x in d if d.index(x) > 0)}'

它会是这样的:

_id = ['1', '2', '3','4']
transport = ['http','tcp','https','dns']
agent = ['10.10.1.1','10.10.1.2','10.10.1.3','10.10.1.4']
username = ['DESKTOP-123\\user','root','user','user']
os = ['windows/amd64','linux/amd64','windows/amd64','linux/amd64']
seen = ['2019-08-31 13:10:08','2019-08-31 13:10:08','2019-08-31 13:10:08','2019-08-31 13:10:08']
titles = ['ID', 'Transport', 'Agent', 'Username','Operating System','Last Seen']
data = [titles] + list(zip(_id, transport, agent, username,os,seen))

def os():
print("\t")
for i, d in enumerate(data):
line = f'{str(d[0]).ljust(18)}| {"| ".join(str(x).ljust(17) for x in d if d.index(x) > 0)}'
print(line)
if i == 0:
sep = '-' * 18 + '+'
line = ''.join(sep for x in d)
print(line)
print("\t")

结果:

ID                | Transport        | Agent            | Username         | Operating System | Last Seen        
------------------+------------------+------------------+------------------+------------------+------------------+
1 | http | 10.10.1.1 | DESKTOP-123\user | windows/amd64 | 2019-08-31 13:10:08
2 | tcp | 10.10.1.2 | root | linux/amd64 | 2019-08-31 13:10:08
3 | https | 10.10.1.3 | user | windows/amd64 | 2019-08-31 13:10:08
4 | dns | 10.10.1.4 | user | linux/amd64 | 2019-08-31 13:10:08

关于python - 格式化表 ascii python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57741573/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com