我想从Python字符串中除去破折号和空格以外的所有特殊字符。如何从Python字符串中删除空格和破折号以外的所有特殊字符?
这是正确的吗?
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'
如图所示,我最终要去除其他特殊字符后,以取代下划线的空间,但想我会做的阶段。是否有一种Pythonic方法可以一举完成这一切?
对于上下文,我将这个输入用于MongoDB集合名称,所以希望最终字符串的约束为:允许使用破折号和下划线的字母数字。