Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Removing all occurrences of any characters in the word 'dust' in the string

Example:

Input:             Output:
dustbin            bin
if 'dust' in string:
  new = string.split('dust')
  listToStr = ''.join(map(str, new))
  print(listToStr)

The above code works fine.

But if the input changes like this.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Input:                       Sample Output:
dustduuuustdustbin            bin

The above code doesn’t work. Is there a solution to this?

>Solution :

Use a regular expression.

import re

result = re.sub(r'[dust]', '', string)

The regexp [dust] matches any of those characters, and all the matches are replaced with an empty string.

If you want to remove only the whole word dust, with possible repetitions of the letters, the regexp would be r'd+u+s+t+'.

If only u can be repeated, use r'du+st'.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading