无法删除@4N_McrAirport

问题描述 投票:0回答:2

所以我只需要删除以“@”开头的单词。

我需要把它从

@sam_mie_J @4N_McrAirport @airfrance I can't describe my feelings.
对此
I can't describe my feelings.
我一开始试过这个

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`
python string string-conversion
2个回答
0
投票

您可以使用正则表达式删除以

@
开头的任何单词,如下所示:

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

aa
将是这个字符串:
"I can't describe my feelings."

如果你不想使用正则表达式,你可以将字符串拆分成单词并根据第一个字符进行过滤然后重新加入,就像这样:

aa = ' '.join(i for i in mm.split() if i[0] != '@').strip()

这也应该给出相同的所需输出字符串

"I can't describe my feelings."


0
投票

re
模块将简化此工作:

import re
test_string = "@sam_mie_J @4N_McrAirport @airfrance I can't describe my feelings."
pattern = "\@\w* "
print(re.sub(pattern, "", test_string))
© www.soinside.com 2019 - 2024. All rights reserved.