I need to append/format a URL with a list of ids for an API call.
However, when I put the list at the end of the API:
https://api.twitter.com/1.1/users/lookup.json?user_id=%s'%a
I just get an empty string as a response.
I have tried turning the list into a string and removing the square brackets, doing:
a = str(followers['ids'])[1:-1]
but I still get the same problem. I'm assuming that it's being caused by the single quote at the start.
I have tried removing the apostrophe from the string doing:
a.replace("'", "")
and now I have run out of ideas.
I have tried removing the apostrophe from the string doing ...
You can remove apostrophe from a string using s = s.replace("'", ""). .replace() returns a new string but does not change the orginal string so you'll to store the returned string.
>>> string = "he's a jolly good fellow"
>>> string = string.replace("'", "")
>>> string
'hes a jolly good fellow'
But I don't think that's not your problem.
The ids need to be comma separated, so you'll probably want to use a .join() to create the string from your list of ids. Example:
>>> ids = ["1", "23", "123"]
>>> ",".join(ids)
'1,23,123'
In your case, assuming followers['ids'] contain a list of id as strings, you can generate your URL using:
ids = ",".join(followers['ids']) # generate string of ids (comma separated)
url = "https://api.twitter.com/1.1/users/lookup.json?user_id=%s" % ids
If followers['ids'] is a list of integers instead of string, then there's a little more work to do since .join() works only with a sequence of strings. Here's one way to convert those integers to string on the fly (using a generator expression):
ids = ",".join(str(id) for id in followers['ids'])
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With