在Python中,确定字符串是电子邮件还是整数的最快方法是什么?

发布于 2024-08-27 05:42:07 字数 424 浏览 10 评论 0原文

我希望能够使用提供的电子邮件地址或用户 ID(整数)从数据库中提取用户。为此,我必须检测提供的字符串是整数还是电子邮件。寻找最快的方法来做到这一点。谢谢。

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']
    ...

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']
    ...

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

木緿 2024-09-03 05:42:07

在 Python 中处理这个问题的规范方法是先尝试,再请求宽恕:

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

这个策略也被称为 “请求宽恕比请求许可更容易”

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".

早乙女 2024-09-03 05:42:07

您可以使用 isinstance 函数:

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

虽然就个人而言,我只有两个方法、fetchByIdfetchByEmail 来明确其工作原理。

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.

乖乖公主 2024-09-03 05:42:07

你说两者都是字符串,对吗?这也行。

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

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

if data.isdigit():
    # it's an id
else:
    # it's not
断肠人 2024-09-03 05:42:07
if '@' in data:
    # email
else:
    # id
if '@' in data:
    # email
else:
    # id
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文