python - Better way to remove multiple words from a string? -


bannedword = ['good','bad','ugly']  def removebannedwords(toprint,database):     statement = toprint     x in range(0,len(database)):         if bannedword[x] in statement:             statement = statement.replace(bannedword[x]+' ','')     return statement  toprint = 'hello ugly guy, see you.'  print removebannedwords(toprint,bannedword) 

the output hello guy, see you. knowing python feel there better way implement changing several words in string. searched similar solutions using dictionaries didn't seem fit situation.

here's solution regex:

import re  def removebannedwords(toprint,database):     statement = toprint     pattern = re.compile("\\b(good|bad|ugly)\\w", re.i)     return pattern.sub("", toprint)  toprint = 'hello ugly guy, see you.'  print removebannedwords(toprint,bannedword) 

Comments

Popular posts from this blog

android - Pass an Serializable object in AIDL -

php - Improving script execution time -

How to provide Authorization & Authentication using Asp.net, C#? -