How to do multiple string replacements in a cleaner manner? - Python
Question: What is a fast way of doing multiple string.replace? I'm trying to add spaces
to shorten english words like

    
    
    he'll -> he 'll
    he's -> he 's
    we're -> we 're
    we've -> we 've
    

also i'm adding spaces in between before and punctuation as such:

    
    
    "his majesty" ->  " his majesty " 
    his; majesty -> his ; majesty
    

Is there a faster and cleaner way to do it? It's a little too slow for the
purpose but I've been doing it this way:

    
    
    def removeDoubleSpace(sentence):
      sentence.replace("  ", " ")
      if "  " in sentence:
        removeDoubleSpace(sentence)
    
    def prepro(sentence):
      sentence = sentence.replace(",", " ,")
      sentence = sentence.replace(";", " ; ")
      sentence = sentence.replace(":", " : ")
      sentence = sentence.replace("(", " ( ")
      sentence = sentence.replace("(", " ) ")
      sentence = sentence.replace("‘"," ‘ ")
      sentence = sentence.replace('"',' " ')
      sentence = sentence.replace("'re", " 're")
      sentence = sentence.replace("'s", " 's")
      sentence = sentence.replace("'ll", " 'll")
      sentence = removeDoubleSpace(sentence)
      return sentence
    


Answer: You could use a few regular expressions to accomplish the same task:

    
    
    import re
    
    # Replace multiple consecutive spaces with a single space
    # Example: "One Two  Three    Four!" -> "One Two Three Four!"
    sentence = re.sub(' +', ' ', sentence)    
    
    # Surround each instance ; : ( ) ‘ and " with spaces
    # Example: '"Hello;(w)o:r‘ld"' -> " Hello ;  ( w ) o : r ‘ ld "
    sentence = re.sub('([;:()‘"])', ' \\1 ', sentence)
    
    # Insert a space before each instance of , 's 're and 'll
    # Example: "you'll they're, we're" -> "you 'll they 're , we 're"
    sentence = re.sub("(,|'s|'re|'ll)", ' \\1', sentence)
    
    return sentence
    

