leozilla
leozilla

Reputation: 1346

Filter strings not starting with a certain name in python

I have a list of database names and I want to exclude those which start with postgres.

So if I have [ "postgres", "post", "postgres2", "custom1", "custom2" ] the result should be [ "post", "custom1", "custom2" ]

I tried two different variants but both did not yield the result I was looking for:

either: f_dbs = [d for d in all_dbs if not d.startswith("postgres")]

or: f_dbs = list(filter(lambda d: not d.startswith("postgres"), all_dbs))

f_dbs_str = "\n".join(f_dbs)
print(f"Postgres databases to drop:\n{f_dbs_str}")

Both dont exclude anything from the list. How should I write this?

Edit: I updated the question with the additional usage of the filtered list, the output always prints postgres as well.

Edit: I found the problem, all the items in the list had a leading whitespace, after striping all those, it works as expected.

Upvotes: 2

Views: 1732

Answers (2)

AbyxDev
AbyxDev

Reputation: 1575

>>> all_dbs = [ "postgres", "post", "postgres2", "custom1", "custom2" ]
>>> [d for d in all_dbs if not d.startswith('postgres')]
['post', 'custom1', 'custom2']

Your first solution works for me. You just need to set it to a variable:

>>> filtered_dbs = [d for d in all_dbs if not d.startswith('postgres')]
>>> filtered_dbs
['post', 'custom1', 'custom2']

Upvotes: 2

Andrew McDowell
Andrew McDowell

Reputation: 2980

The first of those methods create a new list, rather than modifying the original and the second creates an iterator which you can convert to a list fairly easily.

list_of_dbs = [ "postgres", "post", "postgres2", "custom1", "custom2" ]

filtered_list = [item for item in list_of_dbs if not item.startswith("postgres")]

print(filtered_list)
>>> ['post', 'custom1', 'custom2']

filter_iterator = filter(lambda d: not d.startswith("postgres"), list_of_dbs)

print(filter_iterator)
>>><filter object at 0x10339d470>

print(list(filter_iterator))
>>>['post', 'custom1', 'custom2']

Upvotes: 1

Related Questions