简体   繁体   中英

In python, what is the fastest way to determine if a string is an email or an integer?

I'd like to be able to pull users from a database using either a supplied e-mail address or the user id (an integer). To do this, I have to detect if the supplied string is an integer, or an e-mail. Looking for the fastest way to do this. Thanks.

def __init__(self, data):
    #populate class data
    self._fetchInfo(data)


def _fetchInfo(self, data):
    #If an email
        #SELECT ... WHERE email = 'data'
    #or if a user_id
        #SELECT ... WHERE id = 'data'

    #Fill class attributes 
    self._id = row['id']
    self._email = row['id']
    ...

The canonical way to handle this in Python is to try first, ask forgiveness later:

def _fetchInfo(self, data):
    try:
        data=int(data)
        sql='SELECT ... WHERE id = %s'
        args=[data]
    except ValueError:
        sql='SELECT ... WHERE email = %s'
        args=[data]
        # This might fail, in which case, data was neither a valid integer or email address

This strategy also goes by the moniker "It is Easier to Ask for Forgiveness than Permission" .

You can use the isinstance function:

if isinstance(data, int):
   # it's an id
else:
   # it's a string

Though personally, I'd just have two methods, fetchById and fetchByEmail to make it clear that's how it works.

You said both were strings, right? This would work, too.

if data.isdigit():
    # it's an id
else:
    # it's not
if '@' in data:
    # email
else:
    # id

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