Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python adding number to string

Tags:

python

Trying to add a count int to the end of a string (website url):

Code:

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

I want:

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

Results:

Traceback (most recent call last):
  File "grub.py", line 7, in <module>
    Url = Url + (count)
TypeError: cannot concatenate 'str' and 'int' objects
like image 727
jokajinx Avatar asked Aug 17 '12 03:08

jokajinx


1 Answers

The problem is exactly what the traceback states. Python doesn't know what to do with "hello" + 12345

You'll have to convert the integer count into a string first.

Additionally, you never increment the count variable, so your while loop will go on forever.

Try something like this:

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

Or even better:

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

As Just_another_dunce pointed out, in Python 2.x, you can also do

print url + str(count)
like image 51
Joel Cornett Avatar answered Oct 25 '22 19:10

Joel Cornett