Get specific word from a sentence if it has a certain character

Solution 1:

You can also use regex for your purposes. In this regex pattern \S* means "Any non-whitespace character". You can test the regular expression here.

import re

string = 'My email is [email protected] and I use it a lot.'

search_word = re.search(r'(\S*)@(\S*)', string)
if search_word:
    print(search_word.group())
else:
    print("Word was not found.")

Solution 2:

Using list comprehension:

emails = [i for i in string.split() if '@' in i]

Output:

['[email protected]']

Solution 3:

Use regular expression to extract your pattern of interest, for example:

import re
email = re.search('\w+@\w+([.]\w+)+', string).group(0)

Solution 4:

match=re.search(r'([^\s]*@[^\s]*)',string)
if match and match.group(0): print(match.group(0))