删除部分字符串并添加到另一个

2024-04-26 13:41:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我有这样的弦

str1 = "https://web2.some.com/hbh/productImages?itemId=5986546"
str2 = "https://web2.some.com/hbh/productImages?itemId=5986546231"
str3 = "https://web2.some.com/hbh/productImages?itemId=22432"

如何将最后的数字“5986546”、“5986546231”、“22432”添加到其他字符串。你知道吗

我的意思是我只需要从字符串中删除"https://web2.some.com/hbh/productImages?itemId="部分。当然,这个数字的长度也会有所不同。你知道吗


Tags: 字符串httpscom数字someweb2itemidstr1
3条回答

对字符串使用split函数。你知道吗

str1.split("https://web2.some.com/hbh/productImages?itemId=")[-1]

由于您的URL不包含多个=,因此可以使用str.split

id = str1.split('=')[-1] # or [1] in this case no diff

对于单个参数,可以使用标准库中的^{}

from urllib.parse import urlparse

str1 = "https://web2.some.com/hbh/productImages?itemId=5986546"

item1 = urlparse(str1).query.split('=')[-1]  # '5986546'

对于多个参数,可以通过^{}构造字典:

from urllib.parse import urlparse, parse_qs

str2 = "https://web2.some.com/hbh/productImages?itemId=5986546&somevar=5"

args = parse_qs(urlparse(str2).query)
item2 = args['itemId']  # '5986546'

相关问题 更多 >