How can I prepend each value of a list with either a loop or a function?

Viewed 24

I'm currently making API calls to an application and then parsing the JSON data for certain values. The values I'm parsing are suffixes of a full URL. I need to take this list of suffixes and prepend them with my variable which completes each URL. This list can vary in size and so I will not always know the exact list length nor the exact values of the suffixes.

The list (worker_uri_list) will consist of the following format: ['/api/admin/configuration/v1/vm/***/', '/api/admin/configuration/v1/vm/***/'], '/api/admin/configuration/v1/vm/***/']. The asterisk are characters that can vary at any given time when the API call is made. I need to then prepend each one of these suffixes with my variable (url_prefix).

I'm having a hard time trying to understand the best method and how to do this correctly. Very new to Python here so I hope I've explained this well enough. It seems a simple for or while loop could accomplish this, but a lot of all the loop examples I find are for simple integer values.

Any help is appreciated.

url_prefix = "https://website.com"
url1 = url_prefix + "/api/admin/configuration/v1/config"
payload={}
header = {
  'Authorization': 'Basic ********'
}

#Parse response
response = requests.get(url1, headers=header).json()
worker_uri_list = nested_lookup("resource_uri", response)

loop?
function?
1 Answers

You could iterate the worker_uri_list in a loop:

for uri in worker_uri_list:
    url = url_prefix + uri
    # do something with the url
    print(url)

Output:

https://website.com/api/admin/configuration/v1/vm/***/
https://website.com/api/admin/configuration/v1/vm/***/
https://website.com/api/admin/configuration/v1/vm/***/

Or if you want a list of URLs, use a list comprehension:

urls = [url_prefix + uri for uri in worker_uri_list]
print(urls)

Output:

[
 'https://website.com/api/admin/configuration/v1/vm/***/',
 'https://website.com/api/admin/configuration/v1/vm/***/',
 'https://website.com/api/admin/configuration/v1/vm/***/'
]
Related