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("_"))))) the_answer_is_42
Is there any simpler solution?
My approach is:
split()the original string into a list by
- Remove all empty strings from this list by
if not x==''.
'_'.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==''])
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)