2012-06-08 46 views
0

我有一個字符串像rdb_master_mongodb其中rdb_是固定的,master是它可以是任何東西,mongodb可以是一間mysqlmongodbpostgresmssqlbdb數據庫名稱。我需要從myDict[master][mongodb]中的值中獲取該字符串的值。爲了得到這個,我需要分割字符串rdb_master_mongodb並得到mastermongodb的值。我無法使用拆分,因爲有時字符串變成rdb_master_test_mongodb。因此我必須使用endswith才能得到確切的關鍵。 Howeveer,endswith不能在列表上工作。我需要從元組中獲得匹配的元組值。現在我這樣做:Python字典優化這個腳本

import re 
name = 'rdb_master_mongodb' 
s = re.sub('rdb_', "", name) 
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb') 
(a, b, c, d, e) = VALID_DB 
if s.endswith(a): 
    db = a 
if s.endswith(b): 
    db = b 
if s.endswith(c): 
    db = c 
if s.endswith(d): 
    db = d 
if s.endswith(e): 
    db = e 
db_name = re.sub('_'+db, "", s) 
print db_name+" is "+db 

有沒有更好的方法來做到這一點?

回答

1

如果name格式始終是相同的,你可以把它先分成幾部分:

rdb, temp = name.split('_', 1) 
master, db = temp.rsplit('_', 1) 

然後檢查db是否有效:

VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb') 
if db in VALID_DB: 
    ... 

然後使用這三個變量rdb, master, db來構建所需的字符串。

+0

'rdb,master,db ='rdb_master_test_mongodb'.split('_')'給出'ValueError:太多值來解包'。 –

+0

我認爲你應該分裂兩次。 – iMom0

+0

@LevLevitsky - 你是對的,那麼我們必須分兩次。答案已更新。 – eumiro

1
db = name.rsplit('_', 1)[1] 
if db not in VALID_DB: 
    raise ValueError('Incorrect DB name: %s' % db) 
+1

'.rpartition()'的工程,即使「_」是不是在字符串 – jfs

+0

@ lev-levitsky這適用於我的需要。 – bubby

+0

@bubby很高興幫助。考慮接受答案(如果有幫助)(左邊的勾號)。 –

0

因此,只有這個詞到底是顯著,如果我理解你很好,在這種情況下,我想嘗試:

>>> VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb') 
>>> name = 'rdb_master_mongodb' 
>>> db_name = [db for db in VALID_DB if name.endswith(db)][0] 
>>> db_name 
'mongodb' 
>>> name_test = 'rdb_master_test_mongodb' 
>>> db_name = [db for db in VALID_DB if name_test.endswith(db)][0] 
>>> db_name 
'mongodb' 
+0

'.endswith'忽略'_'的位置,並接受'「xxx_badmysql」.endswith('mysql')'。 – eumiro

+0

@emmanuel感謝您的建議。 – bubby