Home > Software engineering >  How to remove a word from a list with a specific character in a specific index position
How to remove a word from a list with a specific character in a specific index position

Time:12-08

this is what I have so far:

wlist = [word for word in wlist if not any(map(lambda x: x in word, 'c'))]

this code works, however in its current state it will remove all strings from wlist which contain 'c'. I would like to be able to specify an index position. For example if

wlist = ['snake', 'cat', 'shock']
wlist = [word for word in wlist if not any(map(lambda x: x in word, 'c'))]

and I select index position 3 than only 'shock' will be removed since 'shock' is the only string with c in index 3. the current code will remove both 'cat' and 'shock'. I have no idea how to integrate this, I would appreciate any help, thanks.

CodePudding user response:

Simply use slicing:

out = [w for w in wlist if w[3:4] != 'c'] 

Output: ['snake', 'cat']

CodePudding user response:

Probably you should use regular expressions. How ever I don`t know them )), so just iterates through list of words.

for i in wlist:
try:
    if i[3] == 'c':
        wlist.remove(i)
except IndexError:
    continue

CodePudding user response:

First, you need to check 'c' exist in word or not then check the index.

wlist = ['snake', 'cat', 'shock']
result = [w for w in wlist if not ('c' in w and w.index('c') == 3)]
# ---------------------with this : ^^^^^^^^ if 'c' does not exist in word, we don't need to check the index and don't get any error.
# for checking for multiple index:
# result = [w for w in wlist if not ('c' in w and w.index('c') in [3, 7, 10])]
print(result)
# ['snake', 'cat']

CodePudding user response:

You should check only the 3rd character in your selected string. If you use the [<selected_char>:<selected_char> 1] list slicing then only the selected character will be checked. More about slicing: https://stackoverflow.com/a/509295/11502612

Example code:

checking_char_index = 3
wlist = ["snake", "cat", "shock", "very_long_string_with_c_char", "x", "c"]
out = [word for word in wlist if word[checking_char_index : checking_char_index   1] != "c"]
print(out)

As you can see, I have extended your list with some corner-case strings and it works as expected as you can see below.

Output:

>>> python3 test.py 
['snake', 'cat', 'very_long_string_with_c_char', 'x', 'c']
  • Related