我有一个类似于rdb_master_mongodb
的字符串,其中rdb_
是固定的,master
是一个数据库名称,可以是任何东西,mongodb
可以是mysql
、mongodb
、postgres
、mssql
或bdb
中的一个。我需要从字典中获取这个字符串的值,它的值在myDict[master][mongodb]
中。为了得到这个,我需要分割字符串rdb_master_mongodb
,并得到master
和mongodb
的值。我不能使用split,因为有时字符串会变成rdb_master_test_mongodb
。因此,我必须使用endswith
来获得确切的密钥。然而,endswith
在列表上不起作用。你知道吗
我必须从一个元组中得到匹配的元组值。现在我这样做:
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
有没有更好的办法?你知道吗
所以只有单词的结尾才有意义,如果我能很好地理解你,在这种情况下,我会尝试:
如果
name
的格式始终相同,则可以先将其拆分为多个部分:然后检查
db
是否有效:然后使用这三个变量
rdb, master, db
构建所需的字符串。你知道吗相关问题 更多 >
编程相关推荐