在特殊字符前添加空格

2024-10-01 22:41:43 发布

您现在位置:Python中文网/ 问答频道 /正文

如何在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.'

有什么解决这个问题的建议吗?在


Tags: and字符串reis单词likebutstrong
3条回答

问题是你也在替换角色。您需要在regex中使用group来保存它,然后在替换字符串中指定group number。在

>>> myString = 'I like him, but is he good? Maybe he is good , smart, and strong.'
>>> re.sub(r'(\w)([,?!])' , r'\1 \2' ,myString)
'I like him , but is he good ? Maybe he is good , smart , and strong.'

您可以使用^{}

>>> import re
>>> myString= 'I like him, but is he good? Maybe he is good , smart, and strong.'
>>> re.sub('(?<=\w)([!?,])', r' \1', myString)
'I like him , but is he good ? Maybe he is good , smart , and strong.'
>>>

(?<=\w)是与单词字符匹配的回溯断言。在

([!?,])是与字符集[!?,]匹配的捕获组(您可以在方括号内添加更多要匹配的字符)。在

\1是指([!?,])捕获的文本。在

作为另一种回答,您可以在不使用regex的情况下解决它,只需使用str.replace

>>> rep_list=['?',',','!']
>>> for i in rep_list : 
...  if i in myString:
...   myString=myString.replace(i,' '+i)
... 
>>> myString
'I like him , but is he good ? Maybe he is good  , smart , and strong.'

相关问题 更多 >

    热门问题