0

So, I have this URL: https://www.last.fm/music/Limp+Bizkit/Significant+Other

I want to split it, to only keep the Limp+Bizkit and Significant+Other part of the URL. These are variables, and can be different each time. These are needed to create a new URL (which I know how to do).

I want the Limp+Bizkit and Significant+Other to be two different variables. How do I do this?

  • The canonical question is *[How can I split a URL string up into separate parts in Python?](https://stackoverflow.com/questions/449775/)* (2009). – Peter Mortensen Nov 28 '22 at 02:35

3 Answers3

3

You can use the str.split method and use the forward slash as the separator.

>>> url = "https://www.last.fm/music/Limp+Bizkit/Significant+Other"
>>> *_, a, b = url.split("/")
>>> a
'Limp+Bizkit'
>>> b
'Significant+Other'
Łukasz Kwieciński
  • 14,992
  • 4
  • 21
  • 39
1

You can replace https://www.last.fm/music/ in the URL to just get Limp+Bizkit/Significant+Other. Then you can split it in half at the / character to break it into two strings. Then the URL will be a list and you can access the indices with url[0] and url[1]:

>>> url = "https://www.last.fm/music/Limp+Bizkit/Significant+Other"
>>> url = url.replace("https://www.last.fm/music/",'').split('/')
>>> first_value = url[0]
>>> second_value = url[1]
>>> first_value
'Limp+Bizkit'
>>> second_value
'Significant+Other'
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
dio
  • 112
  • 1
  • 13
0

You can use regular expressions to achieve this.

import regex as re

url = "https://www.last.fm/music/Limp+Bizkit/Significant+Other"
match = re.match("^.*\/\/.*\/.*\/(.*)\/(.*)", url)

print(match.group(1))
print(match.group(2))
dasJulian
  • 497
  • 6
  • 21