Suppose there is a list
primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
now If I waned to separate elements with ".txt " to get into a new separate list how can I do that?
Suppose there is a list
primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
now If I waned to separate elements with ".txt " to get into a new separate list how can I do that?
As shown in Nk03's answer and quamrana's comment, you can use list comprehension to create a new list. To add to this, if you would like to filter specifically a suffix, use the endswith() method. Otherwise, items will get filtered out, even if .txt happens to appear somewhere else in the text.
primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
new_list = [item for item in primary_list if not item.endswith('.txt')]
new_list_two = [item for item in primary_list if item.endswith('.txt')]
print(new_list)
print(new_list_two)
Output:
['f1', 'f2', 'f3']
['t1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
you can use list comprehension with string split method -
new_list_without_txt = [item for item in primary_list if '.txt' not in item ]
new_list_with_txt = [item for item in primary_list if '.txt' in item ]
print(new_list_without_txt)
print(new_list_with_txt)
output--
['f1', 'f2', 'f3']
['t1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
primary_list=['f1', 'f2', 'f3', 't1.txt', 't2.txt', 't3.txt', 't4.txt', 't5.txt']
new_list = [item.split('.txt')[0] if '.txt' in item else item for item in primary_list]
print(new_list)
output -
['f1', 'f2', 'f3', 't1', 't2', 't3', 't4', 't5']