Python 程式檢查字串是否包含任何唯一字元
在本教程中,我們將編寫一個程式來檢查字串是否包含任何特殊字元。它在 Python 中很簡單。
我們在 string 模組中有一組特殊字元。我們可以用它來檢查字串是否包含任何特殊字元。讓我們來看看編寫程式的步驟。
匯入 string 模組。
將 string.punctuation 中的特殊字元儲存在變數中。
初始化一個字串。
使用 map 函式檢查字串是否具有特殊字元。
列印結果,無論是否有效。
示例
# importing the string module import string # special characters special_chars = string.punctuation # initializing a string string_1 = "Tutori@lspoinT!" string_2 = "Tutorialspoint" # checking the special chars in the string_1 bools = list(map(lambda char: char in special_chars, string_1)) print("Valid") if any(bools) else print("Invalid") # checking the special chars in the string_2 bools = list(map(lambda char: char in special_chars, string_2)) print("Valid") if any(bools) else print("Invalid")
輸出
如果你執行上面的程式,你會得到以下結果。
Valid Invalid
結論
可以將程式碼移動到一個函式中,避免程式碼中的冗餘。如果你對本教程有任何疑問,請在評論部分中提及。
廣告