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

Asked 2 weeks ago, Updated 2 weeks ago, 1 views

I'm a beginner at Python.

When there is a list below,

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

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:

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

© 2022 pinfo. All rights reserved.