在Python中,确定字符串是电子邮件还是整数的最快方法是什么?
我希望能够使用提供的电子邮件地址或用户 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
在 Python 中处理这个问题的规范方法是先尝试,再请求宽恕:
这个策略也被称为 “请求宽恕比请求许可更容易”。
The canonical way to handle this in Python is to try first, ask forgiveness later:
This strategy also goes by the moniker "It is Easier to Ask for Forgiveness than Permission".
您可以使用 isinstance 函数:
虽然就个人而言,我只有两个方法、
fetchById
和fetchByEmail
来明确其工作原理。You can use the isinstance function:
Though personally, I'd just have two methods,
fetchById
andfetchByEmail
to make it clear that's how it works.你说两者都是字符串,对吗?这也行。
You said both were strings, right? This would work, too.