Sounds like a job for the regex module. Also worth a comment so people understand what this is trying to do. At the very least this function needs a docstring.