Regex version of strip() - Ch. 7 Automate the Boring Stuff
If you call regex_strip(s, ""), you will get:


  re.error: unterminated character set at position 0


because neither ^[] nor []$ is a valid regular expression.  You could avoid this by using if not chars: instead of if chars == None:.



There is no need to re.compile() your regular expressions; you aren't saving the compiled patterns anywhere for re-use.



You can simplify your logic by using the reg-ex to capture the middle, non-stripped portion of the string, instead of doing two replacements for the start and end trim operations:

import re

def regex_strip(s, chars = None):

    if chars:
        trim = '[' + re.escape(chars) + ']*'
    else:
        trim = r'\s*'

    return re.fullmatch(f"{trim}(.*?){trim}", s).group(1)




I'm not sure the point of asking you to write your own strip() function is to delegate the task to the reg-ex engine.  It seems like going out and buying a sledge hammer when the problem is to build a nut cracker.