I am new to python. I need help figuring out how do I remove a word from a list of strings that contains special characters?
x = ["I", "@prerkls", "saw"]
How do I remove the word that contain the @ sign?
CodePudding user response:
As was told, there can be a case where you can't reassign the list to variable, but have to edit the existing one. So the simplest approach is iterating over list and poping items
for index, word in enumerate(x):
if '@' in word:
x.pop(index) # better than list.remove()
CodePudding user response:
The below will remove the non-desirable words from the original list of words (mutates the input list).
def remove(words, special):
wr_idx = 0 # effectively the new size of the modified list
for curr_idx in range(len(words)):
if special in words[curr_idx]: # remove by not copying back
continue
words[wr_idx] = words[curr_idx]
wr_idx = 1
del words[wr_idx:]
For your case we'd do:
x = ["I", "@prerkls", "saw"]
remove(x, '@')
print(x)
Output
['I', 'saw']