从两个不同标题下的循环打印输出

时间:2018-03-26 19:40:56

标签: python python-3.x sorting format grouping

我想尝试格式化输出以列在标题下。

我制作了一个python(v3.6)脚本,用于检查网址(包含在纺织品中)和输出是否安全或恶意。

循环声明:

"""
This iterates through each url in the textfile and checks it against google's database.
"""

f = open("file.txt", "r")

for weburl in f:

    sb = threat_matches_find(weburl) # Google API module

    if url_checker == {}:  # the '{}' represent = Safe URL
        print ("Safe :", url)

    else:
        print ("Malicious :", url)

结果是:

>>>python url_checker.py 
Safe : url1.com
Malicious : url2.com
Safe : url3.com
Malicious: url4.com
Safe : url5.com 

目标是让网址在标题(组)下列出/排序,如下所示:

如果网址是安全的,请在“安全网址”下打印网址,否则输入“恶意”。

>>> python url_checker.py
Safe URLs:
url1.com
url3.com
url5.com

Malicious URLs:
url2.com
url4.com

我找不到与我的问题相关的其他帖子是不成功的。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:2)

您可以在循环时附加到列表,然后在填充两个列表时打印:

safe = []
malicious = []
for weburl in f:
    sb = threat_matches_find(weburl) # Google API module
    if url_checker == {}:  # the '{}' represent = Safe URL
        safe.append(url)
    else:
        malicious.append(url)

print('Safe URLs', *safe, '', sep='\n')
print('Malicious URLs', *malicious, '', sep='\n')

示例输出:

safe = ['url1.com','url3.com','url5.com']
malicious = ['url2.com','url4.com']

Safe URLs
url1.com
url3.com
url5.com

Malicious URLs
url2.com
url4.com