Python Forum

Full Version: Extract email addresses from string and store them in a list
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I extract email addresses from a string and store them in a list? The following code produces the desired output when printed in the for loop, but I am not sure how to store them in one accessible list.

text = 'Emails: [email protected], [email protected], [email protected]'
text = text.split()

for word in text:
    if '@' in word:
        emails = word
        emails = emails.replace(',', '')
        emails = emails.split()
        print(emails)
Output:
['[email protected]'] ['[email protected]'] ['[email protected]']
Little bit refactored with usage of list comprehension: 'give me chunk without ending comma for every chunk in list of chunks from text if chunk contains @'.


>>> text = 'Emails: [email protected], [email protected], [email protected]'
>>> [chunk.rstrip(',') for chunk in text.split() if '@' in chunk]
['[email protected]', '[email protected]', '[email protected]']
Perfect! Thank you.