I'm curious to know the most "pythonic" way to check if there is an item in a list of strings that contains a given substring.
For example, say we have a list of email addresses:
['email1@abc.com', 'anotheremail@grandmasSMTPserver.net', 'myboss@dontemailme.org']
and we need to send an email to most of the emails in this list, but not all of them. What is the simplest (read: most "pythonic") way to check for a list element that contains the substring, say, 'dontemailme.org'
and then remove it from the list?
I'm mainly concerned with determining whether an item in the list contains the substring, ideally which item in particular, so that I can make corresponding adjustments to the list.
I come from a C++ background so my initial thought is to use a for
loop with an if
statement to check but I am often surprised at the flexibility of Python.
You can use list comprehension :
emails = ['email1@abc.com', 'anotheremail@grandmasSMTPserver.net', 'myboss@dontemailme.org']
output_list = [email for email in emails if 'dontemailme.org' not in email]
print(output_list) # output: ['email1@abc.com', 'anotheremail@grandmasSMTPserver.net']
filter
is one way:
filtered = filter(lambda email: 'dontemailme.org' not in email, emails)
I would use a list comprehension:
emails = ['email1@abc.com', 'anotheremail@grandmasSMTPserver.net', 'myboss@dontemailme.org']
filtered_emails = [email for email in emails if "dontemailme.org" not in email]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.