8

尝试将 count int 添加到字符串(网站 url)的末尾:

代码:

  count = 0
  while count < 20:
    Url = "http://www.ihiphopmusic.com/music/page/" 
    Url = (Url) + (count)
    #Url = Url.append(count)
    print Url

我想:

http://www.ihiphopmusic.com/music/page/2
http://www.ihiphopmusic.com/music/page/3
http://www.ihiphopmusic.com/music/page/4
http://www.ihiphopmusic.com/music/page/5

结果:

Traceback (most recent call last):
  File "grub.py", line 7, in <module>
    Url = Url + (count)
TypeError: cannot concatenate 'str' and 'int' objects
4

7 回答 7

20

问题正是回溯状态。Python 不知道该怎么办"hello" + 12345

您必须count先将整数转换为字符串。

此外,您永远不会增加count变量,因此您的 while 循环将永远持续下去。

尝试这样的事情:

count = 0
url = "http://example.com/"
while count < 20:
    print(url + str(count))
    count += 1

甚至更好:

url = "http://example.com/"
for count in range(1, 21):
    print(url + str(count))

正如 Just_another_dunce 所指出的,在 Python 2.x 中,您也可以这样做

print url + str(count)
于 2012-08-17T03:06:56.307 回答
5

尝试

 Url = (Url) + str(count)

反而。问题是您试图连接一个字符串和一个数字,而不是两个字符串。str()将为您解决此问题。

str()将提供count适合连接的字符串版本,而无需实际count从 int 转换为字符串。看这个例子:

>>> n = 55

>>> str(n)
>>> '55'

>>> n
>>> 55

最后,格式化字符串被认为比连接它更有效。IE,

 Url = '%s%d' % (Url, count)

或者

 Url = '{}{}'.format(Url, count)

此外,你有一个无限循环,因为循环count内的值永远不会改变。要修复此添加

count += 1

在循环的底部。

于 2012-08-17T03:04:34.673 回答
3

尝试将 count 转换为字符串,如

Url = "http://www.ihiphopmusic.com/music/page/" + str(count)

或使用格式

Url = "http://www.ihiphopmusic.com/music/page/%s" % count

甚至可能

Url = "http://www.ihiphopmusic.com/music/page/{count}".format(count=count) 
于 2012-08-17T03:05:31.443 回答
2

用这个:

url = "http://www.ihiphopmusic.com/music/page/" while count < 20: '''You can redefine the variable Also, you have to convert count to a string as url is also a string''' url = url + str(count) print url

于 2018-01-17T19:23:53.800 回答
1
Url = "http://www.ihiphopmusic.com/music/page/%d" % (count,)
于 2012-08-17T03:05:41.287 回答
0

您必须将 int 更改为字符串。

Url = (Url) + str(count)
于 2012-08-17T03:05:45.687 回答
0

您需要将整数转换为字符串

count = 0
while count < 20:
    Url = "http://www.ihiphopmusic.com/music/page/"
    Url = (Url) + str(count)     
    #Url = Url.append(count)     
    print Url 
于 2012-08-17T03:06:02.253 回答