How to slicing url?

62 Views Asked by At

I want to slice my url from https://exemple.com/key-system-1?hwid=07f8f20b7419f622&zone=Europe/Rome to hwid=07f8f20b7419f622.

I tried

url = "https://exemple.com/key-system-1?hwid=07f8f20b7419f622&zone=Europe/Rome"
uirl = url[: url.find("hwid")]
print (uirl)

But the result is

https://exemple.com/key-system-1?
4

There are 4 best solutions below

0
Ohad Sharet On

The problem in your code is that you used : wrong when you tried to slice the string

url = old_url[:index]

means that the new value of url is the part of old_url from 0 to index

and

url = old_url[index:]

means that the new value of url is the part of old_url from index to the end of `old_url

in conclusion to get the result you are locking for you could use the following code

url = "https://exemple.com/key-system-1?hwid=07f8f20b7419f622&zone=Europe/Rome"
url_slice_1 = url[url.find("hwid"):]
url_slice_2 = url_slice_1[:url_slice_1.find("&")]
print (url_slice_2 )
0
sahasrara62 On

Use a exisiting lib with which you can parse a whole url and get differnet componets easily. dont go for string slicing approach in this case. you can achive this with urllib

with urllib you can do this as

>>> url = "https://exemple.com/key-system-1?hwid=07f8f20b7419f622&zone=Europe/Rome"
>>> import urllib
>>> query_parms = urllib.parse.urlparse(url).query
>>> query_parms
'hwid=07f8f20b7419f622&zone=Europe/Rome'
>>> query_parms_dict = urllib.parse.parse_qs(query_parms)
>>> query_parms_dict
{'hwid': ['07f8f20b7419f622'], 'zone': ['Europe/Rome']}
4
Mr. Irrelevant On

You could use regex:

x = re.search("hwid=.*&", yourURL)

after that trim the last sign to get rid of the &

result = x[:-1]
0
Suramuthu R On
url = 'https://exemple.com/key-system-1?hwid=07f8f20b7419f622&zone=Europe/Rome'

#The actual start-idx is not the index of hwid= as the indx of hwid= is the index of the first letter of hwid= i.e 'h'
# So count the numbers of rest of the letters in hwid= and 1 to it to get the start_index( 4 + 1 = 5)

st = url.find('hwid=') + 5

end = url.find('&zone')
sliced_url = url[st:end]
print(sliced_url)  #Output: 07f8f20b7419f622