Python] Make a list by pulling only those with specific phrases from the list

Asked 2 years ago, Updated 2 years ago, 44 views

I'm a beginner at Python.

When there is a list below,

textname = ["A.txt","A.srt","B.txt","B.srt"]

If there is a value with "txt", is there a code to add to the new list?

I don't think it's much, but I can't find it.

Desired Results

textfile = ["A.txt","B.txt"]

python list

2022-09-20 12:33

2 Answers

I don't know how to be a beginner

for i in textname:
    if 'txt' in i:
        textfile.append(i)


2022-09-20 12:33

There's also a function. There's a function called filter.

textfile = filter(lambda e: 'txt' in e, textname)

Or you can write in one line as a list compliance.

textfile = [ e for e in textname if 'txt' in e ]


2022-09-20 12:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.