Search code examples
pythonpython-3.xcharacteremail-validation

Validating where the "@" symbol is in an email. Not validation of the email itself


"it must contain an “@” symbol which is NEITHER the first character nor the last character in the string."

So I have this assignment in my class and I can't for the life of me figure out how to make the boolean false for having it at the front or end of the email. This is what I have so far.

def validEmail1(myString):
    for i in myString:
        if i == "@":
            return True
    else:
        return False

Solution

  • With s as your string, you can do:

    not (s.endswith('@') or s.startswith('@')) and s.count('@')==1
    

    Test:

    def valid(s):
        return not (s.endswith('@') or s.startswith('@')) and s.count('@')==1
    
    cases=('@abc','abc@','abc@def', 'abc@@def')
    
    for case in cases:
        print(case, valid(case))
    

    Prints:

    @abc False
    abc@ False
    abc@def True
    abc@@def False
    

    You can also use a slice, but you also need to make sure (indirectly) that the string does not start or end with '@' by making sure the count is 1:

    def valid(s):
        return '@' in s[1:-1] and s.count('@')==1