简体   繁体   English

对于循环,如果元素不等于值,则用空字符串替换

[英]For loop, if element does not equal value, replace with empty string

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' 我正在尝试摆脱数字和空格,基本上不是“ a”,“ b”或“ 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']

You're misunderstanding how or works: 您误会了如何or如何工作:

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 ). 并因此始终为True (因为b值为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. 字符串是不可变的,并且通过将''分配给i ,您根本不需要更改字符串。 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']

Use re.sub to replace everything that is not a , b , or c , ie, [^abc] , with an empty string: 使用re.sub用空字符串替换不是abc ,即[^abc]

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

DEMO . 演示

  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]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM