-2

I have a problem. I can't figure out a way to do this so I'm asking for someone to help.

I have URL like below:

https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4

And, I want to remove the last part of URL and change /f/ with /d/ so that I can get the URL to be like below:

https://abc.xyz/d/b 

Keep in mind the prefix /b. It changes regular python. I have tried this below based on url answer but it didsn't work for me.

newurl = oldurl.replace('/f/','/d/').rsplit("/", 1)[0])
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129

4 Answers4

2

A more efficient way of splitting is to use rsplit and set maxsplit to 1. This saves you the time and hassle rejoining the string.

old_url = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
url = old_url.rsplit("/", 1)[0]
# print(url) => https://abc.xyz/f/b
Taku
  • 31,927
  • 11
  • 74
  • 85
  • i have updated the question i have tried to add ur answer but i didnt' succeed newurl = oldurl.replace('/f/','/d/').rsplit("/", 1)[0]) – Mouhcin Iuoanid May 12 '18 at 16:18
  • @MouhcinIuoanid it works fine https://ideone.com/9V9w0i. I can see from your comment that you had an extra ) at the end. – Taku May 12 '18 at 16:43
1

This what you want?

'/'.join(url.split('/')[:-1])
Justin
  • 61
  • 5
0

You don't really need regex for this. The following will work for a link:

k = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
print("/".join(k.split("/")[:-1]))
Martin Gergov
  • 1,556
  • 4
  • 20
  • 29
0

After split() or rsplit(), sometimes you will want and need to specify and get the list of element from the front then join() them and replace() f with d as shown below:

url = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
new_url = "/".join(url.split("/")[:5]).replace("f", "d")
print(new_url)
url = "https://abc.xyz/f/b/go_cc_Jpterxvid_avi_mp4"
new_url = "/".join(url.rsplit("/")[:5]).replace("f", "d")
print(new_url)

Output:

https://abc.xyz/f/b
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129