AlTs
AlTs

Reputation: 301

Remove separated by characters special symbols from string

How to remove special symbols /#$%^&*@0123456789 only if they are separated from each other by characters or symbols not in the list. For example:

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

I know that simple string.replace will not work here. I tried something like this but it didn't work either:

 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)

Upvotes: 1

Views: 79

Answers (2)

Ajax1234
Ajax1234

Reputation: 71471

You can try this:

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^!'))

Output:

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

Upvotes: 1

dejanualex
dejanualex

Reputation: 4358

I know it is not exactly what you asked, but a first validation can be made based on .islapha() e.g:

 def validate(s):
    text=''
    for i in s:
        if i.isalpha():
            text+=i
        else:
          pass
     return text

Upvotes: 0

Related Questions