Q:

Python replace part of long url

I have a long url like
https://yyyyyy.com/yyyyy/xxxxx/yyyyy/yyyyyy/yyyyy/pppp/kkkk

And I want to replace the xxxx part to zzzz
I tried with the re.sub
b = url.split('/')[-6] #which gives me the right part of the url to change
newurl = re.sub(b, 'zzzz',  url)

But when i print it i still get the old url.. Any idea? 

A:

You can do it with replace.
url = 'https://yyyyyy.com/yyyyy/xxxxx/yyyyy/yyyyyy/yyyyy/pppp/kkkk'
sp = url.split('/')[-6]
new_url = url.replace(sp, 'zzzz')

print(new_url)

Output
https://yyyyyy.com/yyyyy/zzzz/yyyyy/yyyyyy/yyyyy/pppp/kkkk

Be careful, because this will replace all the 'xxxx' in your url. For example if you have.
url = 'https://yyyyyy.com/xxxxx/xxxxx/xxxxx/yyyyyy/xxxxx/pppp/kkkk'
sp = url.split('/')[-6]
new_url = url.replace(sp, 'zzzz')

print(new_url)

Output
https://yyyyyy.com/zzzzz/zzzz/zzzzz/yyyyyy/zzzzz/pppp/kkkk

