Search code examples
pythonweb-scrapingstring-concatenation

How to insert one string into another?


I want to insert each string from player id into url and concatenate the entire string so that I can scrape the url. When I do this in python I get the error

url = "https://rotogrinders.com/players/",player_id[x],"?format=json"
TypeError: list indices must be integers or slices, not str
player_id = ["stephen-curry-1079","rodney-hood-18629","c-j-mccollum-17121","damian-lillard-13900","enes-kanter-13299",
    "andre-iguodala-1334","draymond-green-13976","klay-thompson-13315","andrew-bogut-1494","zach-collins-37866","kevon-looney-18945",
    "al-farouq-aminu-1279","evan-turner-1291","seth-curry-16825","shaun-livingston-14007","jonas-jerebko-1106","maurice-harkless-16971",
    "jordan-bell-37877","quinn-cook-31771","alfonzo-mckinnie-37808","meyers-leonard-13905","jake-layman-35216"]

x = 0
for x in player_id:
    url = "https://rotogrinders.com/players/",player_id[x],"?format=json"
    x+=1

Solution

  • Basically, the x is a string already, but you're treating it like an integer.

    You can do simply:

    for x in player_id:
        url = "https://rotogrinders.com/players/" + x + "?format=json"
    

    Or, in Python 3:

    url = f"https://rotogrinders.com/players/{x}?format=json"