【问题标题】:Python: Concatenate URL and IntegerPython:连接 URL 和整数
【发布时间】:2012-07-16 18:06:52
【问题描述】:

我正在尝试根据循环的迭代连接 url 和整数。但我收到错误:TypeError: not all arguments converted during string formatting

for i in range(0,20):
    convertedI = str(i)
    address = 'http://www.google.com/search?q=%s&num=100&hl=en&start='.join(convertedI) % (urllib.quote_plus(query))

我也尝试了 urllib.urlencode 函数,但最终得到了同样的错误。

我想我应该提到除了查询之外,这是一个我在我的 main 中传递的字符串我想将当前迭代值分配给 url 中的 start 参数 > &start=1

所以第一次迭代我希望我的网址为

http://www.google.com/search?q=%s&num=100&hl=en&start=1' % (urllib.quote_plus(query))

【问题讨论】:

    标签: python string url urllib2 string-concatenation


    【解决方案1】:
    for i in range(0, 20):
        address = 'http://www.google.com/search?q=%s&num=100&hl=en&start=%s' % (urllib.quote_plus(query), i)
    

    无需使用str,因为%s 隐含地为您执行此操作。也不需要join,因为join 用于在一个序列中获取多个字符串并使用连接字符将它们拉到一起。您只需要简单的字符串格式。

    【讨论】:

    • 这不会在 URL 中的任何地方使用i,而问题显然是这样的。
    • @DavidRobinson 是的,原来的结构让我很困惑,我认为他的意思是将i 连接到最后,所以我更新了我的答案
    • 我已将问题编辑得更清楚。很抱歉有任何混淆。
    【解决方案2】:

    我认为您误解了 join 的作用。它使用它的参数作为分隔符来连接传递序列的元素:

    >>> ','.join(['a', 'b', 'c'])
    'a,b,c'
    

    听起来你只是想做"http://..." + convertedI,但不清楚你到底想做什么。您希望convertedIurllib.quote_plus(query) 值在字符串中的哪个位置?

    【讨论】:

    • 我试过这个,但我得到 TypeError: not all arguments convert during string formatting address = 'google.com/search?q=%s&num=100&hl=en&start=' + convertI % (urllib.quote_plus(query))
    • 你为什么要在里面放一个分号?正如您所拥有的,您必须在 url 和 convertedl 周围加上括号(否则操作顺序会尝试将查询添加到 convertedl 字符串)。不过,Daniel DiPaulo 的回答是最好的。
    猜你喜欢
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-07-18
    • 2011-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多