-2

so i just have to remove the words starting with "@".

i need to convert this from @sam_mie_J @4N_McrAirport @airfrance I can't describe my feelings. to this I can't describe my feelings. and i have tried this at first

mm="@sam_mie_J @4N_McrAirport @airfrance I can't describe my feelings."
aa=mm.split(" ")
for jj in aa:
    if jj.startswith("@"):
        
        aa.remove(jj)
aad=' '.join(aa)
print(aad)```
and the output is

"@4N_McrAirport I can't describe my feelings."

this aint removing the `@4N_McrAirport`
  • Does this answer your question? [Python: Removing list element while iterating over list](https://stackoverflow.com/questions/6022764/python-removing-list-element-while-iterating-over-list) – Pranav Hosangadi Apr 20 '23 at 15:08

1 Answers1

1

You can use regex for removing any word starting with @ like this :

import re
aa = re.sub(r"@\w+", "", mm).strip()

aa would be this string: "I can't describe my feelings."

If you don't want to use regex, you can split the string into words and filter on basis of the first char and then rejoin, like this :

aa = ' '.join(i for i in mm.split() if not i.startswith('@')).strip()

This should also give the same desired output string "I can't describe my feelings."

Note : The reason your code is failing to do what you want it to do is that you're modifying the list while iterating through it. In the first iteration it gets the word at 0th index @sam_mie_J and removes it. Now in the second iteration it's 0th item is @4N_McrAirport and 1st item is @airfrance but it is trying to remove the item at 1st index - which is actually @airfrance. You can modify your input string to the following :

m2 = "@sam_mie_J @user2 @user3 @user4 @user5 @user6 @4N_McrAirport @airfrance I can't describe my feelings."

to understand this better. You'll notice multiple words starting with @ are being missed by your code.

The minimal change you can do in your code is to make a shallow copy of the list while iterating through it like this :

for jj in aa[:]:
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56