Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a string from a list that startswith prefix in python

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?

like image 986
EerlijkeDame Avatar asked Apr 30 '14 22:04

EerlijkeDame


People also ask

How do I remove a prefix from a list in Python?

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() .

How do you strip a prefix from a string in Python?

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 .

How do you remove certain strings from a list in Python?

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.


1 Answers

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.

like image 108
Greg Hewgill Avatar answered Oct 13 '22 21:10

Greg Hewgill