KHajnalka
KHajnalka

Reputation: 11

Removing all characters from python list except some capital letter

I have a list in python which contains a lot of different characters, for example space, |, >, numbers, and small letters, but I only want to keep some capital letter (A,B,C,D). If I try this, it doesen't work, I almost get the desired list, but not only A,B,C,D remain.

with open("text.mfa") as f:
     content = f.read()
mylist = list(content)

letters = ['A','B','C','D']
i = 0
while i < (len(mylist)-1)
     if mylist[i] != letters[0] or letters[1] or letters[2] or letters[3]
            mylist.remove(mylist[i])
     i+=1

Upvotes: 0

Views: 2636

Answers (5)

Taku
Taku

Reputation: 33724

You can use a for loop instead of a while loop since for loop iterates over a set number of values. To check if the word is in letters you can do this:

with open("text.mfa") as f:
     mylist = list(f.read())
mynewlist = []
letters = ['A','B','C','D']
for word in mylist:
      if word not in letters: #if word is not in letters
            mynewlist.append(word) #adds the word to a new list

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114330

A more Pythonic way would probably be to use a list comprehension and the in operator:

mylist = [x for x in content if x in letters]

Upvotes: 2

Javo
Javo

Reputation: 474

Try using filter.

myfilteredlist = list(filter(lambda s: s in letters, mylist))

Upvotes: 2

rsz
rsz

Reputation: 177

Use in instead of or (this check if the element is in the list).

if not mylist[i] in letters:
    mylist.remove(mylist[i])

Upvotes: 0

rmeertens
rmeertens

Reputation: 4451

Let's take a look at your if statement:

if mylist[i] != letters[0] or letters[1] or letters[2] or letters[3]

If put in brackets python processes this as:

if (mylist[i] != letters[0]) or (letters[1]) or (letters[2]) or (letters[3]):

Every character evaluates to True, to this means that because letters[1] etc. evaluate to true you always evaluate your whole expression to True.

Upvotes: 0

Related Questions