[SOLVED] replace multiple non-space characters in python string


Uniting multiple spaces to one space character in a python string is doable (here), but what about uniting non-space-characters?

>>> name = "the__answer____is___42"
>>> print("_".join(list(filter(lambda x: x != '', name.split("_")))))

Is there any simpler solution?


My approach is:

  1. split() the original string into a list by '_'.
  2. Remove all empty strings from this list by if not x==''.
  3. Use '_'.join() on this list.

That would look like this (working code example) :

# original string
targetString = "the__answer____is___42"

# answer
answer = '_'.join([x for x in targetString.split('_') if not x==''])

# printing the answer

You can make that more compact by putting it into a function:

def shrink_repeated_characters(targetString,character):
    return character.join([x for x in targetString.split(character) if not x==''])

In shrink_repeated_characters() given above, the parameter targetString is the original string, and character is the character you want to merge, eg. '_'.

Answered By – AashvikT

Answer Checked By – Cary Denson (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *