'Split from list in python
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/']
Solution 1:[1]
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']
Solution 2:[2]
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/']
Solution 3:[3]
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/']
Solution 4:[4]
Here are the steps I would do:
- split the string after
ewwassuming 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.
Solution 5:[5]
You can use a regex in a list comprehension.
A perfect use case for the new walrus operator (python ?3.8):
List=['a/c/d/eww/d/df/rr/e.jpg',
'ss/dds/ert/eww/ees/err/err.jpg',
'fds/aaa/eww/err/dd.jpg']
import re
out = [m.group() if (m:=re.search('eww/(.*)/', s)) else s
for s in List]
output:
['eww/d/df/rr/', 'eww/ees/err/', 'eww/err/']
NB. this keeps the original string in case of no match, if you rather want to drop it:
out = [m.group() for s in List if (m:=re.search('eww/(.*)/', s))]
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | TaQuangTu |
| Solution 2 | |
| Solution 3 | zeeshan12396 |
| Solution 4 | Emely h |
| Solution 5 | mozway |
