Home > Net >  slicing an string after a word in python
slicing an string after a word in python

Time:12-25

So my issue is I have a string/URL:

"https://www.youtube.com/watch?v=FOoMXn3N5ME&list=PL5E1B8DFA8A07A9FA"

And I want to trim the

"https://www.youtube.com/watch?v=FOoMXn3N5ME&list="

Leaving only the playlist Id which is:

"PL5E1B8DFA8A07A9FA"

I know I could do something with slicing and indexing like

string = string[0:49]

but for my application the input link/URL will vary in size and the playlist id or video id will change the length of the string. So how can I trim this string directly after the

list=

Possibly needed resources: python: 3.8.10 pip: 20.0.2

CodePudding user response:

Instead of trying to slice the string and handling all sorts of potential edge cases, I'd use urllib.parse:

from urllib.parse import *
url = "https://www.youtube.com/watch?v=FOoMXn3N5ME&list=PL5E1B8DFA8A07A9FA"
list_id = parse_qs(urlparse(url).query)['list'][0]

CodePudding user response:

If you don't want to have to import anything.

link = "https://www.youtube.com/watch?v=FOoMXn3N5ME&list=PL5E1B8DFA8A07A9FA"
index = link.find('list')
ID = link[index 5:-1]    

I used the find() method to find the index of the word 'list'. Then I did the rest from there.

  • Related