Home > OS >  replace multiple non-space characters in python string
replace multiple non-space characters in python string

Time:03-23

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?

CodePudding user response:

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
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. '_'.

CodePudding user response:

According to your reference:

>> import re
>> re.sub('_ ', '_', 'the__answer____is___42')
'the_answer_is_42'

# if u have more than one non-space char
>> re.sub(r'([_ ]) ', r"\1", 'the__answer____is___42')
'the_answer_is_42'

>> re.sub(r'([_ ]) ', r"\1", 'the  answer    is   42')
'the answer is 42'
  • Related