【问题标题】:In python, what is the fastest way to determine if a string is an email or an integer?在python中,确定字符串是电子邮件还是整数的最快方法是什么?
【发布时间】:2010-03-30 03:11:01
【问题描述】:

我希望能够使用提供的电子邮件地址或用户 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']
    ...

【问题讨论】:

标签: python string integer


【解决方案1】:

在 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

这个策略也被称为"It is Easier to Ask for Forgiveness than Permission"

【讨论】:

  • 哈哈哈..这就是所有学校都应该教授的try and catch
  • 确保在将任何字符串放入SELECT 语句之前验证输入。
【解决方案2】:

你可以使用isinstance函数:

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

虽然就个人而言,我只有两种方法,fetchByIdfetchByEmail 来说明它是如何工作的。

【讨论】:

  • isinstance 不起作用,因为:“我必须检测是否提供了 string ...” - 它始终是 str. 的实例
  • 哦,是的,我现在明白了……在这种情况下,~unutbu 的回答仍然有效。
【解决方案3】:

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

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

【讨论】:

  • @dan04。没错,但自动递增的 db id 通常不是负数。
【解决方案4】:
if '@' in data:
    # email
else:
    # id

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 1970-01-01
    • 2011-10-10
    • 2014-08-27
    • 2013-08-22
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 2023-02-18
    相关资源
    最近更新 更多