简体   繁体   English

像Powershell这样的Python中的通配符匹配

[英]Wildcard matching in Python like powershell

I'm trying to convert my PowerShell script into python and I'm still learning python. 我正在尝试将PowerShell脚本转换为python,但仍在学习python。

$Check_env = "ProjectNameStaging"
if ($Check_env -like "*Staging") {
    $Environment = "Staging"
}
elseif ($Check_env -like "*Production") {
    $Environment = "Production"
}

I tried to use fnmatch.filter but looks like too much of work in that. 我尝试使用fnmatch.filter,但是在这方面看起来工作太多。

I know it could be done very easily but trying to find the best and less line of code in python for PowerShell scripts because I'm still figuring out to find out how much Python can be used in place of PowerShell. 我知道可以很容易地做到这一点,但是尝试在python中为PowerShell脚本找到最好和更少的代码行,因为我仍然想找出可以使用多少Python代替PowerShell。

Thanks for your help. 谢谢你的帮助。

You can use fnmatch.fnmatch for wildcard matching. 您可以使用fnmatch.fnmatch进行通配符匹配。 Its usage is fnmatch.fnmatch(string, pattern) , and will return true if string matches with pattern . 它的用法是fnmatch.fnmatch(string, pattern) ,如果stringpattern匹配,则返回true。 The translated code will be 转换后的代码将是

import fnmatch

check_name = "ProjectNameStaging"
if fnmatch.fnmatch(check_name, "*Staging"):
    environment = "Staging"
elif fnmatch.fnmatch(check_name, "*Production"):
    environment = "Production"

In this case you can also use endswith if you're ok with a solution without wildcard matching. 在这种情况下,如果您可以使用没有通配符匹配的解决方案,那么也可以使用endswith As the name suggests, this will only check if the string ends with a particular suffix. 顾名思义,这只会检查字符串是否以特定的后缀结尾。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM