'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?
Solution 1:[1]
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
Solution 2:[2]
Try casting the integer as a string:
name = str(n) + '-' + campaign_name
Solution 3:[3]
Or, use string formatting
name = f"{n}-{campaign_name}"
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Peter Mortensen |
| Solution 2 | Nathan Hellinga |
| Solution 3 | Alter |
