【问题标题】:Python Printing A List IssuePython打印列表问题
【发布时间】:2013-07-21 05:11:49
【问题描述】:

我真的很难弄清楚如何打印到列表中。我想打印我指定的 URL 的服务器响应代码。您知道我将如何更改代码以将输出打印到列表中吗?如果没有,你知道我在哪里可以找到答案吗?我已经搜索了几个星期了。

代码如下:

import urllib2
for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]:
    try:
        connection = urllib2.urlopen(url)
        print connection.getcode()
        connection.close()
    except urllib2.HTTPError, e:
        print e.getcode()

打印:

200

200

我想要:

[200, 200]

【问题讨论】:

    标签: python list csv urllib2 urlopen


    【解决方案1】:

    你真的想要一份清单吗?或者只是像列表一样打印它?无论哪种情况,以下都应该起作用:

    import urllib2
    out = []
    for url in ["http://stackoverflow.com/", "http://stackoverflow.com/questions/"]:
        try:
            connection = urllib2.urlopen(url)
            out.append(connection.getcode())
            connection.close()
        except urllib2.HTTPError, e:
            out.append(e.getcode())
    print out
    

    它只是创建一个包含代码的列表,然后打印该列表。

    【讨论】:

    • 差不多,您可能还想在错误上捕获代码。
    • 我继续为你修复了那部分。
    • 太棒了。感谢@sberry 和 Matthew Wesly 的快速回复!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-03-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-02
    • 1970-01-01
    • 2013-07-05
    相关资源
    最近更新 更多