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

前端 未结 11 1412
北海茫月
北海茫月 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:45

    This will work for any number of consecutive asterisks, although you may need to replace the tilde with some other string that you know will be unique throughout the string.

        string = "begin*************end"
    
        string.replace("**", "~*").replace("*~", "").replace("~*", "*").replace("**", "*")
    

    I believe regex approaches would be generally more computationally expensive than this.

提交回复
热议问题