2010-03-30 61 views
1

我希望能夠使用提供的電子郵件地址或用戶標識(整數)從數據庫中提取用戶。爲此,我必須檢測提供的字符串是整數還是電子郵件。尋找最快的方法來做到這一點。謝謝。在python中,確定字符串是電子郵件還是整數的最快方法是什麼?

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

使用正則表達式http://docs.python.org/library/re.html#re-syntax – vittore 2010-03-30 03:17:07

回答

4

的正規途徑在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"去。

+2

哈哈哈..這是如何嘗試和catch應在所有學校教授 – Anurag 2010-03-30 03:23:38

+1

確保您驗證在將任何字符串放入'SELECT'語句之前輸入。 – 2010-03-30 09:22:46

+0

「Little Bobby Tables」:http://xkcd.com/327/ – 2010-03-30 11:44:41

2

可以使用isinstance功能:

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

雖然就個人而言,我只是有兩個方法,fetchByIdfetchByEmail,使之清楚,它是如何工作。

+1

isinstance將不起作用,因爲:「我必須檢測提供的**字符串** ...」 - 它將始終是一個實例str。 – detly 2010-03-30 04:14:39

+0

噢,是的,我現在看到了...在這種情況下,〜unutbu的答案仍然有效。 – 2010-03-30 04:26:02

2

你說這兩個都是字符串,對吧?這也會起作用。

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

如果整數可能爲負數,則不起作用。 – dan04 2010-03-30 06:07:22

+2

@ dan04。 確實如此,但自動遞增的db id通常不是負數。 – 2010-03-30 08:14:43

1
if '@' in data: 
    # email 
else: 
    # id 
相關問題