仅当特殊符号/#$%^&*@0123456789由不在列表中的字符或符号分隔时,如何删除它们。例如:

H8e%&l6&%l@8095o a@/9^65$n228d w%e60$$#&9l3@/c6o5m3e --> Hello and welcome
. #$%#^ --> . #$%#^
,. a3%2%1/3$s*0. d8^! -->,. as. d!
I1^/0^^@9t #$%% i/@4#s 11P17/9$M 5^&* a^$45$5$0n&##^4d 6^&&* I $%^$%^ a8@@94%3*m t3120i36&^1r2&^##0e&^d ---> It #$%% is 11PM 5^&* and 6^&&* I $%^$%^ am tired


我知道简单的string.replace在这里不起作用。我尝试过类似的方法,但是它也不起作用:

 def _correct_message(message):
    f = re.match(r'[a-zA-Z][/#$%^&*@0123456789​][a-zA-Z]', message)
    if f is not None:
        message = re.sub('[/#$%^&*@0123456789​]', '', message)

最佳答案

您可以尝试以下方法:

import re
s = "H8e%&l6&%l@8095o a@/9^65$n228d w%e60$$#&9l3@/c6o5m3e"
s1 = "I1^/0^^@9t #$%% i/@4#s 11P17/9$M 5^&* a^$45$5$0n&##^4d 6^&&* I $%^$%^ a8@@94%3*m t3120i36&^1r2&^##0e&^d"
final_string = re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', s)
print(final_string)
new_final_string = re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', s1)
print(new_final_string)
print(re.sub("(?<=[a-zA-Z\.\!])[/#\$\%\^\&\*\@0123456789]+(?=[a-zA-Z\.\!])", '', ',. a3%2%1/3$s*0. d8^!'))


输出:

'Hello and welcome'
It #$%% is 11PM 5^&* and 6^&&* I $%^$%^ am tired
,. as. d!

关于python - 从字符串中删除用字符分隔的特殊符号,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/47145666/

10-14 19:20
查看更多