Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm trying to get one single word out of a string if it contains a certain character.

I want to do something like this:

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

if '@' in string:
    return email

But how can I get python to know exactly where the keyword is and return it's value.

In this case it would return [email protected]

like image 757
Quessts Avatar asked Oct 20 '25 10:10

Quessts


2 Answers

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.")
like image 93
Oleksii Tambovtsev Avatar answered Oct 22 '25 02:10

Oleksii Tambovtsev


Using list comprehension:

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

Output:

['[email protected]']
like image 27
RJ Adriaansen Avatar answered Oct 22 '25 01:10

RJ Adriaansen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!