Zubair Farooq
Zubair Farooq

Reputation: 23

Concatenate a string with an incrementing number

Here is my code:

n = 2
campaign_img = soup.find('div', class_="campaign-img-contain")
name = str(n) + '-' + campaign_name
campaign_pic = request.urlretrieve(campaign_img.img['src'], folder + name + '.png')
print(campaign_pic)
n = n + 1

I want this:

2-campaign_name

3-campaign_name

4-campaign_name

Result:

TypeError: unsupported operand type(s) for +: 'int' and 'str'

What is the best possible solution?

Upvotes: 0

Views: 2292

Answers (3)

Jack Bishop
Jack Bishop

Reputation: 115

As the error suggests, you can’t concatenate an integer and a string together into another string. You want casting. To cast an integer to a string in Python, use the built-in str function.

Replace the line name= n + '-' + campaign_name with name = str(n) + '-' + campaign_name.

More on casting (W3Schools): Python Casting

Upvotes: 1

Alter
Alter

Reputation: 3464

Or, use string formatting

name = f"{n}-{campaign_name}"

Upvotes: 0

Nathan Hellinga
Nathan Hellinga

Reputation: 372

Try casting the integer as a string:

name = str(n) + '-' + campaign_name

Upvotes: 1

Related Questions