我在python中有这样的代码:
def sth(mlist):
for line in mlist:
out = func(param1, param2)
if out:
print " [+] %-15s %20s " % (line, out.rjust(30, '.'))
else:
a = 'Not Covered!!'
print " [-] %-15s %20s " % (target, a.rjust(30, '.'))
并且在运行代码时得到讨厌的输出:
[-] http://a.com .................Not Covered!!
[-] http://abcd.info .................Not Covered!!
[+] http://abcdef.net ....................something
[-] https://c.com .................Not Covered!!
[+] https://efghij.org .................other thing
.
.
.
如何获得此类线程的最佳输出形式,例如:
[-] http://a.com ......................... Not Covered!!
[-] http://abcd.info ..................... Not Covered!!
[+] http://abcdef.net .................... something
[-] https://c.com ........................ Not Covered!!
[+] https://efghij.org ................... other thing
.
.
.
也欢迎使用其他解决方案而不是使用ljust
。
答案 0 :(得分:1)
好吧,由于您可以使用不使用rjust
或ljust
的解决方案,因此可以决定要打印多少.
并减去len
line
。
简短示例:
print(' [+] {0} {1} {2}'.format(line, '.' * (50 - len(line)), out))
答案 1 :(得分:1)
您可以预先计算最长的URL,并左-用点将其对齐,这样可以更好地配对:
In [5]: signs = ['-', '+', '-']
...: URLs = ['http://foo.com', 'http://much_longer_foo.com', 'http://medium_foo.com']
...: tails = ['Longer shouting ending!!', 'different ending', 'Longer shouting ending!!']
...:
...: maxlen = max(map(len,URLs))
...: linefmt = " [{{sign}}] {{URL:.<{maxlen}}}{{tail:.>30}}".format(maxlen=maxlen)
...: for sign,URL,tail in zip(signs,URLs,tails):
...: print linefmt.format(sign=sign, URL=URL, tail=tail)
...:
[-] http://foo.com..................Longer shouting ending!!
[+] http://much_longer_foo.com..............different ending
[-] http://medium_foo.com...........Longer shouting ending!!
如您所见,我改为使用.format
而不是百分比格式。这主要是一个偏好问题。
重要的是,我们首先构建具有最长URL长度的格式字符串,然后使用生成的格式字符串。结果与您预期的结果略有不同:点周围没有空格。如果您坚持要手动添加它们,可以手动添加。
请注意,在python 3.6及更高版本中,您可以使用f-strings更优雅地做到这一点:
In [1]: signs = ['-', '+', '-']
...: URLs = ['http://foo.com', 'http://much_longer_foo.com', 'http://medium_foo.com']
...: tails = ['Longer shouting ending!!', 'different ending', 'Longer shouting ending!!']
...:
...: maxlen = max(map(len,URLs))
...: for sign,URL,tail in zip(signs,URLs,tails):
...: print(f' [{sign}] {URL:.<{maxlen}}{tail:.>30}')
...:
...:
[-] http://foo.com..................Longer shouting ending!!
[+] http://much_longer_foo.com..............different ending
[-] http://medium_foo.com...........Longer shouting ending!!
此外,如您所见,我建议使用单个格式的字符串,并分别传递其符号/ URL /结尾。这将帮助您减少代码重复并减轻可维护性。