the_t_test_1
the_t_test_1

Reputation: 1263

Formatting URLs in list to all have a trailing slash in python

There's some similar questions to this on stackoverflow but none do exactly what I want and my various attempts seem to fail.

I have a list of urls, some have trailing slash, others not... I want to check them and add a slash to those that don't.

url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

for url in url_list:
    if url[len(url)-1] != "/":
        url = url + "/"
    else:
        url = url

print url_list

returns the same list (last two urls still don't have a trailing slash)

['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

why isn't it working? any ideas?

thanks :)

Upvotes: 5

Views: 7572

Answers (3)

tell k
tell k

Reputation: 615

Your url variable is isolated from url_list. You can try this:

for i, url in enumerate(url_list):
    if url.endswith("/"):
        url_list[i] = url + "/"
print(url_list)

Upvotes: 0

Luci
Luci

Reputation: 477

You are not changing url_list. To keep the initial structure of your code, you could try this:

url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

new_urls = []
for url in url_list:
    if url[len(url)-1] != "/":
        new_urls.append(url + "/")
    else:
        new_urls.append(url)
url_list = new_urls

print url_list

You could also use .endswith() as suggested in another answer:

url_list = ['http://google.com/somedirectory/', 'http://google.com/someotherdirectory/', 'http://google.com/anotherdirectory', 'http://google.com/yetanotherdirectory']

new_urls = []
for url in url_list:
    if url.endswith('/'):
        new_urls.append(url)
    else:
        new_urls.append(url + "/")
url_list = new_urls

print url_list

Upvotes: 1

asongtoruin
asongtoruin

Reputation: 10359

The reason why your changes don't work is that when you say url = url + "/" this doesn't edit url in-place in the list. If you want to do it this way, you might be better using enumerate:

for i, url in enumerate(url_list):
    if url[len(url)-1] != "/":
        url_list[i] = url + "/"

print url_list

We could neaten this further by changing url[len(url)-1] to url[-1], which refers to the last character.

But while we're at it, why not use .endswith() and a list comprehension?

url_list = [u if u.endswith('/') else u + '/' for u in url_list]

Upvotes: 14

Related Questions