2
my_list = ['1 ab ac bbba','23 abcba a aabb ab','345 ccc ab aaaaa']

I'm trying to get rid of the numbers and the spaces, basically everything that's not an 'a','b', or 'c'

I tried this but it didn't work and I'm not sure why:

for str in my_list:
    for i in str:
        if i != 'a' or 'b' or 'c':
            i = ''
        else:
            pass

I want to eventually get:

my_list2 = ['abacbbba','abcbaaaabbab','cccabaaaaa']

3 Answers 3

3

You're misunderstanding how or works:

if i != 'a' or 'b' or 'c':

is equivalent to

if (i != 'a') or ('b') or ('c'):

and will therefore always be True (because b evaluates to True).

You probably meant to write

if i != 'a' and i != 'b' and i != 'c':

which can also be written as

if i not in ('a', 'b', 'c'):

or even (since a string can iterate over its characters)

if i not in 'abc':

But even then, you're not doing anything with that information; a string is immutable, and by assigning '' to i, you're not changing the string at all. So if you want to do it without a regex, the correct way would be

>>> my_list = ['1 ab ac bbba','23 abcba a aabb ab','345 ccc ab aaaaa']
>>> new_list = [''.join(c for c in s if c in 'abc') for s in my_list]
>>> new_list
['abacbbba', 'abcbaaaabbab', 'cccabaaaaa']
Sign up to request clarification or add additional context in comments.

Comments

2

Use re.sub to replace everything that is not a, b, or c, i.e., [^abc], with an empty string:

import re
my_list2 = []
for str in my_list:
    my_list2.append(re.sub("[^abc]", "", str))

DEMO.

Comments

0
  m = ['1 ab ac bbba','23 abcba a aabb ab','345 ccc ab aaaaa']
  n=[m[x][m[x].index(" "):] for x in range(len(m))]
  n=[x.replace(" ","") for x in n]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.