0

Hi guys so basically what my _build_url function does is it takes a list and then adds the parameters passed from the list to the url and generates a url.

def _build_url(list_here):
    pulls_url = "http://test.com" + '/{0}/{1}/{2}/{3}'.format(list_here[0],list_here[1],list_here[2],list_here[3])
    print pulls_url #prints http://test.com/a/b/c/d



_build_url(["a","b","c","d]

I have passed 4 items in a list so the url is generated with 4 parameters, what If I want to pass only 2 parameters like _build_url(["a","b"]) and the url should be generated only from those two items in the list like #prints http://test.com/a/b, basically no matter how many parameters I add the url should be generated according to how many items are there in the list.

How do I modify my code for that.

primer
  • 381
  • 1
  • 2
  • 7

1 Answers1

0

Use str.join() with "/" as the separator instead of str.format() to concatenate the URL parts. This will work with lists of arbitrary length:

def _build_url(list_here):
    pulls_url = "http://test.com/{}".format("/".join(list_here))
    return pulls_url
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • what if I have a variable which stores the url like var = "http://test.com" then how do I add the url using the variable pulls_url = var + – primer Nov 29 '17 at 20:49
  • I also had one more question suppose my url is like "http://test.com/" already, how do I handle the trailing slash at the end of com so that there are no two slashes like "http://test.com//" I am creating test cases for this, so had this doubt. – primer Nov 30 '17 at 03:13
  • You can use `var.rstrip("/")` to remove any trailing slashes in the string, then concatenate the rest, e.g.: `var.rstrip("/") + "/" + "/".join(list_here)` – Eugene Yarmash Nov 30 '17 at 06:45