How to replace repeated instances of a character with a single instance of that character in python

前端 未结 11 1417
北海茫月
北海茫月 2020-12-31 00:29

I want to replace repeated instances of the \"*\" character within a string with a single instance of \"*\". For example if the string is \"*

11条回答
  •  天命终不由人
    2020-12-31 00:30

    Well regular expressions wise I would do exactly as JoshD has suggested. But one improvement here.

    Use -

    regex  = re.compile('\*+')
    result = re.sub(regex, "*", string)
    

    This would essentially cache your regex. So subsequent usage of this in a loop would make your regex operations fast.

提交回复
热议问题