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?
If the format of
nameis always the same, you can split it into parts first:then check whether
dbis valid:then use these three variables
rdb, master, dbto build needed strings.