Foundations of Python

94 / 134

Parsing Strings

Suppose there is a series of lines consisting of email ids. In case we want to find out the university email ids in a group of various email ids consisting of both Gmail and university ids. For eg,

data1 = "someone@gmail.com"

Basically, we will check if there is a substring starting with @gmail

We can do this by using the find method .

position = data1.find('@gmail')

The index of @ i.e, 7 gets assigned to the position. It means it has the substring that we are searching for. If the substring is not present it returns -1.

If we have some other information on the line along with email id, we can slice it off using the technique discussed earlier, since we have the position of @ we can find the position of any blank space before and after @ if present and extract the email id out.

We can also mention the position from where we want the find function to start searching. For eg,

position = data1.find('@gmail', 4, 6)

It will search from the index 4 up to index 6.

If we do not mention anything, find returns the position of the substring that occurs for the first time.

INSTRUCTIONS
  • Define a function with the name email_func that takes a str argument and extracts out and returns the first email id. If there is no email id present return False.

  • Return only if there is valid email id. An email id is valid if at least one @ is present in it and no blank spaces. Else, you can return the boolean False. We are keeping the requirement for a valid email simple, requiring only one '@' in it. We do not want you to write an exhaustive check for valid email here.

Example 1 - Input email_func("Crazy Frog") - Output It should return False

Example 2 - Input email_func("this is first abhinav@cloudxlab.com and this is second sandeep@cloudxlab.com") - Output abhinav@cloudxlab.com

Example 3 - Input email_func("a a@") - Output a@



Note - Having trouble with the assessment engine? Follow the steps listed here

Loading comments...