user5732284 user5732284 - 5 months ago 249x
Python Question

split url by python

I have this URL:


i want to have 3 last numbers : item[0] = 3700620, item[1]=3686967 and item[2] = 3700610

i tried this

one = url.split('/')[-1]
two = url.split('/')[-2]

the result of the first one is

and the second one


A non-regex approach would involve using urlparse and a bit of splitting:

>>> import urlparse
>>> parsed_url = urlparse.urlparse(url) 
>>> number1 = parsed_url.path.split("/")[-1]
>>> number2, number3 = urlparse.parse_qs(parsed_url.query)["t:ac"][0].split("/")
>>> number1, number2, number3
('3700620', '3686967', '3700610')

Regex approach:

>>> import re
>>>"/(\d+)\?t:ac=(\d+)/(\d+)$", url).groups()
('3700620', '3686967', '3700610')

where (\d+) are saving/capturing groups that match one or more digits, \? would match a literal question mark (we need to escape it since it has a special meaning), $ would match the end of the string.

You can also name the groups and produce a dictionary:

>>>"/(?P<number1>\d+)\?t:ac=(?P<number2>\d+)/(?P<number3>\d+)", url).groupdict()
{'number2': '3686967', 'number3': '3700610', 'number1': '3700620'}