我有这样的字符串
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="
部分。当然,这个数字的长度可能会有所不同。
答案 0 :(得分:2)
对于单个参数,您可以使用标准库中的urllib.parse
:
from urllib.parse import urlparse
str1 = "https://web2.some.com/hbh/productImages?itemId=5986546"
item1 = urlparse(str1).query.split('=')[-1] # '5986546'
对于多个参数,您可以通过urllib.parse_qs
构建字典:
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'
答案 1 :(得分:0)
对字符串使用split函数。
str1.split("https://web2.some.com/hbh/productImages?itemId=")[-1]
答案 2 :(得分:0)
由于您的网址不包含多个=
,因此您可以使用str.split
id = str1.split('=')[-1] # or [1] in this case no diff
答案 3 :(得分:0)
使用正则表达式:
import re
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"
regex = re.compile(r'(\d+?)$')
l = regex.findall(str1)
print(l)
输出:
C:\Users\Desktop>py x.py
['5986546']
此外,以下代码将一次全部返回:
all_strings = ''.join( [str1,str2,str3])
regex = re.compile(r'(\d{2,})')
l = regex.findall(all_strings)
print(l)
输出:
C:\Users\Desktop>py x.py
['5986546', '5986546231', '22432']