Search code examples
python-3.xpython-re

remove string which contains special character by python regular expression


my code:

s = '$ascv abs is good'
re.sub(p.search(s).group(),'',s)

ouput:

'$ascv abs is good'

the output what i want:

'abs is good'

I want to remove string which contains special character by python regular expression. I thought my code was right but the output is wrong.

How can i fix my code to make the output right?


Solution

  • invalid_chars = ['@'] # Characters you don't want in your text
    
    # Determine if a string has any character you don't want
    def if_clean(word):
        for letter in word:
            if letter in invalid_chars:
                return False
        return True
    
    def clean_text(text):
        text = text.split(' ') # Convert text to a list of words
        text_clean = ''
        for word in text:
            if if_clean(word):
                text_clean = text_clean+' '+word
        return text_clean[1:]
    
    # This will print 'abs is good'
    print(clean_text('$ascv abs is good'))