簡體   English   中英

像Powershell這樣的Python中的通配符匹配

[英]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) ,如果stringpattern匹配,則返回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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM