
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Strings with Non-Required Characters in Python
When it is required to remove strings, which have a non-required character, a list comprehension and the ‘any’ operator is used.
Below is a demonstration of the same −
Example
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)
Output
The list is : ['python', 'is', 'fun', 'to', 'learn'] The character list is : ['p', 's', 'l'] The resultant list is : ['fun', 'to']
Explanation
A list of strings is defined and is displayed on the console.
Another list with characters is defined and displayed on the console.
A list comprehension is used to iterate over the elements and check if any element is not present in the list.
This is stored in a list and assigned to a variable.
This is displayed as output on the console.
Advertisements