python将数字添加到字符串

时间:2012-08-17 03:02:41

标签: python

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

代码:

  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

7 个答案:

答案 0 :(得分:12)

问题正是回溯所说的。 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)

答案 1 :(得分:4)

尝试

 Url = (Url) + str(count)

代替。问题是你试图连接字符串数字,而不是两个字符串。 str()会为您解决此问题。

str()将提供适合串联的字符串版本count,而不实际将count转换为int中的字符串。见这个例子:

>>> n = 55

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

>>> n
>>> 55

最后,格式化字符串被认为更有效,而不是连接它。即,

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

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

此外,您有一个无限循环,因为count的值永远不会在循环内更改。要解决此问题,请添加

count += 1

在你的循环底部。

答案 2 :(得分:2)

尝试将计数转换为字符串,如

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) 

答案 3 :(得分:1)

Url = "http://www.ihiphopmusic.com/music/page/%d" % (count,)

答案 4 :(得分:1)

使用此:

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

答案 5 :(得分:0)

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

Url = (Url) + str(count)

答案 6 :(得分:0)

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

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