Python - 刪除包含任何非必需字元的字串
當需要刪除包含非必需字元的字串時,會使用列表推導和“any”運算子。
下面展示了相同的過程 -
示例
my_list = ["python", "is", "fun", "to", "learn"] print("The list is :") print(my_list) my_char_list = ['p', 's', 'l'] print("The character list is :") print(my_char_list) my_result = [sub for sub in my_list if not any(element in sub for element in my_char_list )] print("The resultant list is :") print(my_result)
輸出
The list is : ['python', 'is', 'fun', 'to', 'learn'] The character list is : ['p', 's', 'l'] The resultant list is : ['fun', 'to']
說明
定義了一個字串列表,並將其顯示在控制檯上。
定義另一個包含字元的列表,並將其顯示在控制檯上。
使用列表推導遍歷元素並檢查列表中是否存在任何元素。
將其儲存在列表中並分配給變數。
將此顯示為控制檯上的輸出。
廣告