0

I have a list of URLs, and I am trying to remove the trailing '/' from all URLs in the list. I have tried all of these variations with no error message, but no removal of the /:

for link in url_list:
   if link.endswith('/'):
      url_list.append(link[:-1])

for link in url_list:
    if link.endswith('/'):
       link = link[:-1]

for link in url_list:
    link = link[:-1] if link.endswith('/') else link

After running these codes I print(url_list) and nothing has changed.

Zoe
  • 27,060
  • 21
  • 118
  • 148
coult
  • 117
  • 1
  • 2
  • 6
  • 1
    Can you show `url_list`? Your current first method (although not optimal) should work, but it adds the the exisiting list, did you mean to append to a new one? – Chris_Rands Jun 14 '18 at 14:00
  • It is a pretty long list so it wouldn't be feasible to list here. The odd thing is that I created a new list with the same content and ran the original code again and it seems to have worked. The main thing is that I want the change to remain when I write it to a csv – coult Jun 14 '18 at 14:40

1 Answers1

2

You first for-loop almost works, although it appends the new formed urls to you existing ones instead of replacing.

A better approach would be to create a new list with list-comprehension and use str.rstrip to remove a trailing /.

Code

url_list = ['googoo.com/foo/', 'wikipidoo.org/bar/', 'stachoverflaw.com/baz']

stripped_urls = [url.rstrip('/') for url in url_list]

print(stripped_urls)

Output

['googoo.com/foo', 'wikipidoo.org/bar', 'stachoverflaw.com/baz']
Olivier Melançon
  • 21,584
  • 4
  • 41
  • 73
  • `url_list.append(link[:-1])` works though (but dosen't create a new list of course) – Chris_Rands Jun 14 '18 at 14:03
  • Note that this works for urls that _don't_ end with a `'/'`, as well. I'd probably use `map` instead of a comprehension, though. – erip Jun 14 '18 at 14:07
  • 1
    @OlivierMelançon Yes! I was just adding the note since your example only shows true positives. Based on my reading of the question, I believe your code will work for OP's requirements. Nice answer. – erip Jun 14 '18 at 14:08
  • @erip good point actually, I will add an url with no trailing / – Olivier Melançon Jun 14 '18 at 14:09
  • `os.path.normpath` would be a possible (questionable) alternative – Chris_Rands Jun 14 '18 at 14:12
  • @Chris_Rands This will not work, an os using \ as separator will replace all / by \. I had the feeling there would be a caveat to this, there it is – Olivier Melançon Jun 14 '18 at 14:16