python - How to slice a list of strings with space delimiter? -
this question has answer here:
- split elements of list in python 5 answers
i have list (original_list) made of multiple strings space in each element below. how create separate list of last string (or file name excluding else) of each element original list?
original_list = ['-rw-rw-r-- 1 root root 134801 nov 2 14:27 aa_base-13.txt', '-rw-rw-r-- 1 root root 58630 nov 2 14:27 aaa_base-extras.txt', '-rw-rw-r-- 1 root root 300664 nov 2 14:27 aaa_base-extras.txt'] expected output th new list should below:
extracted_list
['aa_base-13.txt', 'aaa_base-extras.txt', 'aaa_base-extras.txt']
that's how:
new_list = [x.split()[-1] x in original_list]
please include attempts in future when asking questions.
there no argument passed split
can see , means takes default space. then, newly created sublists sliced , last item taken (that's [-1]
for). try removing see produces.
of course of times in programming (if not always) there many ways task. example this:
new_list = [y item in [x.split() x in original_list] y in item if '.' in y]
with second 1 looking substrings contain dots '.'
. replace '.txt'
. that's more solid way filenames or filenames of specific extension since bound contain @ least 1 dot.
what 2 approaches have in common list comprehensions. core concept in python , suggest looking @ if serious this.
hope helps!
Comments
Post a Comment