python - 如何在一个命令中传递不敏感的标志以匹配?
问题描述
我正在对带有编译模式后面标志的几个键进行不区分大小写的匹配:
def case(string):
switcher = {
re.compile('bronze', re.IGNORECASE):10,
re.compile('carbon', re.IGNORECASE):16,
}
for i in switcher.keys():
if re.match(i, string):
return switcher[i]
return "Invalid: " + string
有没有更聪明的方式来传递标志,所以我不必在每一行都指定它?
解决方案
你根本不必使用re.compile
,真的。re.match
和朋友无论如何都会在内部缓存最后使用的正则表达式模式。
在这里,switcher
已从case
函数中重构出来,因此不会在每次调用时重新计算;此外,我们dict.items()
用于同时获取模式和值。
switcher = {
'bronze': 10,
'carbon': 16,
}
def case(string):
for pattern, value in switcher.items():
if re.match(pattern, string, flags=re.IGNORECASE):
return value
return "Invalid: " + string
但是,根据您的示例,尚不清楚您是否需要正则表达式,或者您是否只需要不区分大小写的子字符串匹配,在这种情况下,将测试字符串小写在计算上会更便宜,然后只需使用if str1 in str2
,就像这样(假设与switcher
上一个示例中的 dict 相同。)
def case_no_re(string):
l_string = string.lower()
for pattern, value in switcher.items():
if pattern in l_string:
return value
return "Invalid: " + string
推荐阅读
- android - Android logcat没有显示异常完整数据?
- python - Pygame 没有正确运行
- excel - Selenium VBA 将数据提取到 Excel 中
- go - 如何在golang中的整数运算中获得最近的int?
- c - fwrite() c 函数写入额外字节
- c++ - 无法找出为什么我得到分段错误
- ruby-on-rails - 在特定时间发送提醒
- amazon-web-services - 广告网络流量和 Lambda 调用不匹配
- c++ - SDL2 程序在最小化时会占用大量内存
- docker - 在没有编排器的情况下使用 docker 完成任务时生成一个工作容器并杀死它