如何替换某个位置的某个字母而不替换另一个相同的字母?例如:text = `"I need help. I need 5.4 dollar."`我试过:a = re.compile('\D(\.)')
print(a.sub('\n',text))然而,输出是"I need hel\n I need 5.4 dolla\n"我怎样才能得到输出"I need help\n I need 5.4 dollar\n"
3 回答

慕斯709654
TA贡献1840条经验 获得超5个赞
您可以使用回顾:
>>> text = "I need help. I need 5.4 dollar."
>>> re.sub(r'(?<=\D)\.', '\n', text)
'I need help\n I need 5.4 dollar\n'
在这种情况下(?<=\D),断言文字前面的字符.不是数字。

茅侃侃
TA贡献1842条经验 获得超21个赞
对于此特定示例,您可以使用正则表达式元字符 \b 来匹配单词的开头或结尾(单词边界)
import re
text = "I need help. I need 5.4 dollar."
a = re.compile('\b(\.)')
print(a.sub('\n',text))
添加回答
举报
0/150
提交
取消