简体   繁体   中英

How to replace certain characters after other certain characters in a string, Python?

I have a string that is holding a URL:

url = http://example.com/1234/hello/

I wish to replace "hello" with "goodbye"

Thank you in advance!

Best Regards

Edit: My apologies, the example I used had a lot of placeholders. For extra clarification, "1234" and "hello" are dynamic and change a lot, so I need a method to replace everything after the 4th "/", if you will.

So far I've tried this, but it deleted the slashes and numbers:

url = re.search(r'(\A.*)0/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)1/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)2/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)3/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)4/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)5/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)6/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)7/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)8/',url,re.DOTALL|re.IGNORECASE).group(1)
url = re.search(r'(\A.*)9/',url,re.DOTALL|re.IGNORECASE).group(1)

You can use .split() and .join() :

split_url = url.split("/")
split_url[4] = "goodbye"
url = "/".join(split_url)

Are you looking for this (python 2.7)?

>>> import re
>>> input = ' http://example.com/1234/hello/'
>>> re.sub('((?:.*?/){4})([^/]+)(/?)', r'\1goodby\3', input)
' http://example.com/1234/goodby/'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM