My approach is:
split() the original string into a list by '_'.
- Remove all empty strings from this list by
if not x==''.
- 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
print(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. '_'.