In my list I have few items, i.e.,
List=['a/c/d/eww/d/df/rr/e.jpg', 'ss/dds/ert/eww/ees/err/err.jpg','fds/aaa/eww/err/dd.jpg']
I want to keep only from 'eww' till last '/'
Modified_list=['eww/d/df/rr/', 'eww/ees/err/err.jpg','eww/err/']
CodePudding user response:
Use find(sub_str)
function.
new_list = [item[item.find("eww"):] for item in List]
print(new_list)
Output:
['eww/d/df/rr/e.jpg', 'eww/ees/err/err.jpg', 'eww/err/dd.jpg']
CodePudding user response:
Try using this list comprehension, assuming that the eww
string is present in all the elements of the input list:
lst = ['a/c/d/eww/d/df/rr/e.jpg', 'ss/dds/ert/eww/ees/err/err.jpg', 'fds/aaa/eww/err/dd.jpg']
modified_list = [x[x.index('eww'):x.rindex('/') 1] for x in lst]
It works as expected:
modified_list
=> ['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']
CodePudding user response:
new_list2=[item[item.find('eww'):item.rfind('/') 1] for item in List]
print(new_list2)
output= ['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']
CodePudding user response:
Here are the steps I would do:
- split the string after
eww
assuming that each string contains 'eww' you can split the string like this:split = 'eww' string.split('eww')[1]
- Now, you have to loop over each character in the remaining string and save the index of the last
/
- Remove everything after the last
/
with the index from step 3:split = split[:splitIndex]
- Now, you just have to put everything in a loop that iterates over the list and execute each of the steps above on each element of the list and save the modified string to the ModiefiedList list.