如何在Python中创建RE,以便在这些特殊字符前面添加空格,?!
如果这些特殊字符与一个单词?在
以下是输入字符串:
myString= 'I like him, but is he good? Maybe he is good , smart, and strong.'
所需输出(如果特殊字符不固定在一个单词上,则不会修改):
^{pr2}$我试过这个:
modifiedString= re.sub('\w,' , ' ,' ,myString)
但它给出了错误的结果。它删除coma之前的最后一个字符,结果示例如下:
modifiedString = 'I like hi , but is he good? Maybe he is goo , smar , and strong.'
有什么解决这个问题的建议吗?在
问题是你也在替换角色。您需要在regex中使用group来保存它,然后在替换字符串中指定group number。在
您可以使用^{} :
(?<=\w)
是与单词字符匹配的回溯断言。在([!?,])
是与字符集[!?,]
匹配的捕获组(您可以在方括号内添加更多要匹配的字符)。在\1
是指([!?,])
捕获的文本。在作为另一种回答,您可以在不使用regex的情况下解决它,只需使用
str.replace
:相关问题 更多 >
编程相关推荐