gpt4 book ai didi

python - 如何替换特定子字符串后的部分字符串

转载 作者:行者123 更新时间:2023-12-01 07:46:19 25 4
gpt4 key购买 nike

使用Python和Selenium。我有多个 URL 作为列表中的字符串。但是我希望能够在字符串中的子字符串之后替换字符串的一部分(字符串的末尾)。

我尝试过替换()。但这只能取代我具体说明的内容。例如这个链接:

https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB

但是,当我浏览 URL 列表时,“sku=”和“planSku”后面的数字会发生变化

    phonePlanLinksRaw = driver.find_elements_by_xpath("//div[starts-with(@class,'deviceListItem')]/a")

phonePlanLinks = [] #contains the links to all phones



for element in phonePlanLinksRaw:
phonePlanLinks.append(str(element.get_attribute('href')))

phonePlanLinks.pop() #removes bring your own phone

# prints all links
numLink = 1
for element in range(len(phonePlanLinks)):
print("phone " + str(numLink) + " : " + phonePlanLinks[element])
numLink += 1

我希望能够在字符串中的某个点之后交换 URL 中的子字符串。

例如: https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB

'https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku= ' 保持

然后我希望能够在“planSku”之后附加我自己的子字符串

最佳答案

您可以使用 .split() 和关键字作为分隔符,然后将关键字和值连接到第一部分:

url = "https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=Freedom%20Big%20Gig%2015GB"
keyword ="planSku="
newValue ="MyValue"
newUrl =url.split(keyword,1)[0]+keyword+newValue
print(newUrl)
# https://shop.freedommobile.ca/devices/Apple/iPhone_XS_Max?sku=190198786135&planSku=MyValue

您还可以使用正则表达式替换(re 模块)

import re
newUrl = re.sub(f"({keyword})(.*)",f"\\g<1>{newValue}",url)

但是您必须小心关键字和 newValue 中的特殊字符(如果需要,您可以使用 re.escape() 进行转义)。

关于python - 如何替换特定子字符串后的部分字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56448193/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com