如何在Python字符串中插入内容?以给URL添加子域名为例
问题原因
你的代码只拼接了URL前12位和子域名,存在两处遗漏:
- 子域名后缺少
.作为域名层级的分隔符,会导致子域名和原有主域名连在一起 - 没有拼接12位索引之后的剩余URL内容,所以输出结果只到子域名就结束了
实现方案
方案1:通用拆分拼接(不依赖固定切片长度,适配http/https等不同协议)
url = 'https://www.exampleurl.com/' subdomain = 'subdomain' # 拆分协议头和域名主体 protocol, domain_part = url.split("://", 1) # 拼接新域名,Python3.9以下版本可把domain_part.removeprefix('www.')替换为domain_part[4:] new_url = f"{protocol}://www.{subdomain}.{domain_part.removeprefix('www.')}"
方案2:补全原有切片写法
如果你能确认所有待处理的URL前缀固定为https://www.(长度正好12位),可以直接补全你原本的写法:
url = 'https://www.exampleurl.com/' new_url = url[:12] + 'subdomain.' + url[12:]
方案3:字符串替换(写法最简单,适配带固定www.前缀的域名)
url = 'https://www.exampleurl.com/' subdomain = 'subdomain' new_url = url.replace('www.', f'www.{subdomain}.')
以上任意方案运行后得到的new_url都是目标格式https://www.subdomain.exampleurl.com/。
内容的提问来源于stack exchange,提问作者sunflower
相关产品推荐
相关产品推荐

