How to remove all special characters except spaces and dashes from a Python string?
<p>I want to strip all special characters from a Python string, except dashes and spaces.  </p>

<p>Is this correct?  </p>

<pre><code>import re
my_string = "Web's GReat thing-ok"
pattern = re.compile('[^A-Za-z0-9 -]')
new_string = pattern.sub('',my_string)
new_string
&gt;&gt; 'Webs GReat thing-ok'
# then make it lowercase and replace spaces with underscores
# new_string = new_string.lower().replace (" ", "_")
# new_string
# &gt;&gt; 'webs_great_thing-ok'
</code></pre>

<p>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?  </p>

<p>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.  </p>