Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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@example.com 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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

In this case it would return email@example.com

>Solution :

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@example.com 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.")
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading