简体   繁体   English

如何在字符串中的其他某些字符之后替换某些字符,Python?

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

I have a string that is holding a URL:我有一个包含 URL 的字符串:

url = http://example.com/1234/hello/网址 = 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.为了额外说明,“1234”和“hello”是动态的并且变化很大,所以如果你愿意的话,我需要一种方法来替换第 4 个“/”之后的所有内容。

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().join()

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

Are you looking for this (python 2.7)?你在找这个(python 2.7)吗?

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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