I have this list of strings and some prefixes. I want to remove all the strings from the list that start with any of these prefixes. I tried:
prefixes = ('hello', 'bye')
list = ['hi', 'helloyou', 'holla', 'byeyou', 'hellooooo']
for word in list:
list.remove(word.startswith(prexixes)
So I want my new list to be:
list = ['hi', 'holla']
but I get this error:
ValueError: list.remove(x): x not in list
What's going wrong?
There are multiple ways to remove whitespace and other characters from a string in Python. The most commonly known methods are strip() , lstrip() , and rstrip() . Since Python version 3.9, two highly anticipated methods were introduced to remove the prefix or suffix of a string: removeprefix() and removesuffix() .
The removeprefix() method of the Python String Object removes prefixes from any string. One needs to supply the prefix as an argument to the removeprefix() method. For example, my_string. removeprefix('xxx') removes the prefix 'xxx' from my_string .
In Python, use list methods clear() , pop() , and remove() to remove items (elements) from a list. It is also possible to delete items using del statement by specifying a position or range with an index or slice.
You can create a new list that contains all the words that do not start with one of your prefixes:
newlist = [x for x in list if not x.startswith(prefixes)]
The reason your code does not work is that the startswith
method returns a boolean, and you're asking to remove that boolean from your list (but your list contains strings, not booleans).
Note that it is usually not a good idea to name a variable list
, since this is already the name of the predefined list
type.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With