I want to strip all special characters from a Python string, except dashes and spaces.
Is this correct?
import re my_string = "Web's GReat thing-ok" pattern = re.compile('[^A-Za-z0-9 -]') new_string = pattern.sub('',my_string) new_string >> 'Webs GReat thing-ok' # then make it lowercase and replace spaces with underscores # new_string = new_string.lower().replace (" ", "_") # new_string # >> 'webs_great_thing-ok' As shown, I ultimately want to replace the spaces with underscores after removing the other special characters, but figured I would do it in stages. Is there a Pythonic way to do it all in one fell swoop?
For context, I am using this input for MongoDB collection names, so want the constraint of the final string to be: alphanumeric with dashes and underscores allowed.