开发者

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

开发者 https://www.devze.com 2022-12-25 15:14 出处:网络
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.Lo

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 em开发者_运维百科ail = '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
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号