Python Forum
Extract email addresses from string and store them in a list
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Extract email addresses from string and store them in a list
#1
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]']
Reply
#2
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]']
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#3
Perfect! Thank you.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  extract substring from a string before a word !! evilcode1 3 531 Nov-08-2023, 12:18 AM
Last Post: evilcode1
Question Need help for a python script to extract information from a list of files lephunghien 6 1,074 Jun-12-2023, 05:40 PM
Last Post: snippsat
  Extract value from a list thesquid 2 849 Nov-29-2022, 01:54 PM
Last Post: thesquid
  store all variable values into list and insert to sql_summary table mg24 3 1,123 Sep-28-2022, 09:13 AM
Last Post: Larz60+
  a function to get IP addresses of interfaces Skaperen 2 1,416 May-30-2022, 05:00 PM
Last Post: Skaperen
  Loop through list of ip-addresses [SOLVED] AlphaInc 7 3,946 May-11-2022, 02:23 PM
Last Post: menator01
  How to store the resulting Doc objects into a list named A xinyulon 1 1,893 Mar-08-2022, 11:49 PM
Last Post: bowlofred
  Extract a string between 2 words from a text file OscarBoots 2 1,864 Nov-02-2021, 08:50 AM
Last Post: ibreeden
  How to extract specific key value pair from string? aditi06 0 2,517 Apr-15-2021, 06:26 PM
Last Post: aditi06
  instance methods sharing addresses mim 1 2,229 Mar-28-2021, 05:22 AM
Last Post: deanhystad

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020