【问题标题】:Split URL in Python在 Python 中拆分 URL
【发布时间】:2021-06-04 19:47:07
【问题描述】:
【问题讨论】:
标签:
python
url
discord.py
last.fm
【解决方案1】:
您可以使用str.split 方法并使用正斜杠作为分隔符。
>>> url = "https://www.last.fm/music/Limp+Bizkit/Significant+Other"
>>> *_, a, b = url.split("/")
>>> a
'Limp+Bizkit'
>>> b
'Significant+Other'
【解决方案2】:
您可以将网址中的https://www.last.fm/music/ 替换为Limp+Bizkit/Significant+Other。然后您可以在/ 字符处将其分成两半,将其分成两个字符串。然后 url 将是一个列表,您可以使用 url[0] 和 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'
【解决方案3】:
您可以使用正则表达式来实现这一点。
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))