简体   繁体   中英

How to check if there's a specific charactar in a string (in Python)

I am coding a little system for fun right now(in Python). I came into trouble while writing a mail-checker. It is supposed to check if a email address contains a '.' and '@'. This is the code:

def check_mail(mail):
    email = str(mail)
    needed_charachters = ['@', '.']
    if needed_charachters[1] not in email:
        print(send_error('Mail invalid (has to contain ".")'))
        return False
    if needed_charachters[0] not in email:
        print(send_error('Mail invalid (has to contain "@")'))
        return False
    elif '.' in email:
        print('contains .') 

I already tried a few techniques but there was everytime the same error. If i put in "ahksdasdhk" as mail there comes my error "has to contain "." " This is alright and what I wanted. But when mail is "gaagsggg@ksdkj.wssf" there still comes the same error. Btw this is my code for ther error creator:

def send_error(message):
    return f'ERROR: {message}'

elif is the issue, Try this:

def check_mail(mail):
    email = str(mail)
    needed_charachters = ['@', '.']
    if needed_charachters[1] not in email:
        print(send_error('Mail invalid (has to contain ".")'))
        return False
    if needed_charachters[0] not in email:
        print(send_error('Mail invalid (has to contain "@")'))
        return False
    else:
        print('Valid mail')
        return True

And would suggest doing it in a loop:

def check_mail(mail):
    email = str(mail)
    needed_charachters = ['@', '.']
    for character in needed_characters:
        if character not in email:
            print(send_error('Mail invalid (has to contain ' + character + ')'))
            return False        
        else:
            print('Valid mail')
            return True

the issue is last elif '.' . you can do something like this

def check_mail(mail):
    email = str(mail)
    if not email.__contains__("@"):
        print(send_error('Mail invalid (has to contain "@")'))
        return False
    if not email.__contains__("."):
        print(send_error('Mail invalid (has to contain ".")'))
        return False
    # if you passed those steps its valid email so
    return True

or simpler

def check_mail(mail):
    email = str(mail)
    needed_charachters = ["@", "."]
    err = [x for x in needed_charachters if x not in email]
    err and print(send_error(f"Mail invalid (has to contain '{err[0]}')"))
    return not bool(err)

however I myself always verify email like this

import re

regex = """^(\w|\.|\_|\-)+[@](\w|\_|\-|\.)+[.]\w{2,3}$"""
is_valid_email = lambda email: bool(re.search(regex, email))

# checking if email is valid or not
print(is_valid_email("the_email_address@info.com"))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM