Reputation: 58
I have a string like rdb_master_mongodb
where rdb_
is fixed and master
is a database name which can be anything and mongodb
can be one among mysql
, mongodb
, postgres
, mssql
or bdb
. I need to fetch the value for this string from the dictionary which has the value in myDict[master][mongodb]
. In order to get this I need to split the string rdb_master_mongodb
and get the values of master
and mongodb
. I can't use split because sometimes the string becomes rdb_master_test_mongodb
. Hence I have to use endswith
to get the exact key. Howeveer, endswith
does not work on a list.
I have to get the matching tuple value from a tuple. Right now I do this like:
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
Is there a better way to do this?
Upvotes: 0
Views: 120
Reputation: 14209
So only the end of the word is significant, if I understand you well, in this case I'd try:
>>> 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'
Upvotes: 0
Reputation: 212835
If the format of name
is always the same, you can split it into parts first:
rdb, temp = name.split('_', 1)
master, db = temp.rsplit('_', 1)
then check whether db
is valid:
VALID_DB = ('mysql', 'postgres', 'mongodb', 'mssql', 'bdb')
if db in VALID_DB:
...
then use these three variables rdb, master, db
to build needed strings.
Upvotes: 1
Reputation: 65791
db = name.rsplit('_', 1)[1]
if db not in VALID_DB:
raise ValueError('Incorrect DB name: %s' % db)
Upvotes: 1