I'm trying to convert my PowerShell script into python and I'm still learning 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.
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.
Thanks for your help.
You can use fnmatch.fnmatch
for wildcard matching. Its usage is fnmatch.fnmatch(string, pattern)
, and will return true if string
matches with pattern
. 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. 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"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.