pythonlistf-string

need a way to update variable to include all input list items, formatted the same way


I'm running a program in python that sends graphql post requests. The query looks like this, :

var = input("string here")

query = f"""query{{item1(item2:"{var}"){{item3{{item4{{item5}}}}}}}}"""

There's nothing wrong with the query itself. But, I would like to query instead, for an entire list, and I would like to do it in one request, rather than one request for each item. This can be accomplished by simply changing the query so that every list item has its own section with a separate alias, so for 2 items in the list, it would look like:

itemlist = [input("Enter items: ").strip().split()][0]

# itemlist now looks like ['listitem1', 'listitem2'] etc.

query = f"""query{{{listitem1}:item1(item2:"{listitem1}"){{item3{{item4{{item5}}}}}}{listitem2}:item1(item2:"{listitem2}"){{item3{{item4{{item5}}}}}}}}"""

and this is just done by copying the item1(item2:"{listitem1}"){{item3{{item4{{item5}}}}}} section and placing it directly after the first one, but with an alias "alias: " tacked onto the front of each, which can just be the listitems as is, hence the {listitem#}:

I've already confirmed that this query works. what I don't know how to do, as i'm very new to python (so, sorry if this post is extremely poorly worded,) is how to do what i just described efficiently: copy that section back to back into the query variable for every item in the list. Thanks for any assistance you can provide.

EDIT: ok, I think I've figured it out like 2 minutes after I posted this. I just do a for loop and append the fully formatted query section with each list item into another list, and then ''.join() that list into the query variable. sorry to be a bother. -_-


Solution

  • If I'm understanding correctly, you could iterate over your input list and concatenate together your query inside the loop. Something like:

    itemlist = [input("Enter items: ").strip().split()][0]
    
    # itemlist now looks like ['listitem1', 'listitem2'] etc.
    
    query = "query{{"
    for item in itemlist:
       query=query + f'{"{item}"}:item1(item2:"{item}"){{item3{{item4{{item5}}}}}}'
    query=query + "}}"
    
    print(query)