e9e9s e9e9s - 1 year ago 59
Python Question

How to use split on individual entries in a list

So I have a python list (called lst in the snippet below) of urls.


I want to create another list of only the /file.zip part of each url. So far I have this:

lst2 = []
for i in lst:

and it returns the /file.zip part as expected. But my question is how can I do this for the entire list?

Answer Source

Assuming lst = [url1, url2, ...], your current code is very close to working optimally.

The last line of the code lst2.append(i[0].split('/')][-1]) is where the problems lie.

By calling i[0] you are essentially getting the first character of the i string (since the i derives from the strings inside lst), and then splitting it based on /, which would not work. Then you have an error with the lone ] after the split.

So, to fix this code, here is what you would do.

lst2 = []
for i in lst:

and then, printing lst2 would give

['file.zip', 'file1.zip', ...]

which is your desired output.

To explain, i in lst is getting every item inside the lst list, which are strings. Then, inside the loop, the string i is being split according to the / inside it, which generates another array. But you want the final part of that string, hence the final item in the array, which can be accessed using [-1].

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download