[英]Wildcard matching in Python like powershell
我正在尝试将PowerShell脚本转换为python,但仍在学习python。
$Check_env = "ProjectNameStaging"
if ($Check_env -like "*Staging") {
$Environment = "Staging"
}
elseif ($Check_env -like "*Production") {
$Environment = "Production"
}
我尝试使用fnmatch.filter,但是在这方面看起来工作太多。
我知道可以很容易地做到这一点,但是尝试在python中为PowerShell脚本找到最好和更少的代码行,因为我仍然想找出可以使用多少Python代替PowerShell。
谢谢你的帮助。
您可以使用fnmatch.fnmatch
进行通配符匹配。 它的用法是fnmatch.fnmatch(string, pattern)
,如果string
与pattern
匹配,则返回true。 转换后的代码将是
import fnmatch
check_name = "ProjectNameStaging"
if fnmatch.fnmatch(check_name, "*Staging"):
environment = "Staging"
elif fnmatch.fnmatch(check_name, "*Production"):
environment = "Production"
在这种情况下,如果您可以使用没有通配符匹配的解决方案,那么也可以使用endswith
。 顾名思义,这只会检查字符串是否以特定的后缀结尾。
check_name = "ProjectNameStaging"
if check_name.endswith("Staging"):
environment = "Staging"
elif check_name.endswith("Production"):
environment = "Production"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.