Regex 不';不能替换所有事件
我试着用正则表达式替换这个字符串中的三个单词。但我只换了最后一批,而不是全部三批Regex 不';不能替换所有事件,regex,python-3.x,Regex,Python 3.x,我试着用正则表达式替换这个字符串中的三个单词。但我只换了最后一批,而不是全部三批 import re input_txt='The quick brown fox jumps over the lazy dog.' dic={'The':'THE', 'fox':'FOX', 'dog':'DOG'} for i,j in dic.items(): output2=re.sub(i,j,input_txt) print(output2) 输出2值: 敏捷的棕色狐狸跳过了懒狗 每次都是从原
import re
input_txt='The quick brown fox jumps over the lazy dog.'
dic={'The':'THE', 'fox':'FOX', 'dog':'DOG'}
for i,j in dic.items():
output2=re.sub(i,j,input_txt)
print(output2)
输出2值:
敏捷的棕色狐狸跳过了懒狗
每次都是从原始的
input\u txt
将替换内容写入新字符串。相反,只需覆盖input_txt
:
input_txt='The quick brown fox jumps over the lazy dog.'
dic={'The':'THE', 'fox':'FOX', 'dog':'DOG'}
for i,j in dic.items():
input_txt=re.sub(i,j,input_txt)
>>> print(input_txt)
THE quick brown FOX jumps over the lazy DOG.
每次都是从原始的
input\u txt
将替换内容写入新字符串。相反,只需覆盖input_txt
:
input_txt='The quick brown fox jumps over the lazy dog.'
dic={'The':'THE', 'fox':'FOX', 'dog':'DOG'}
for i,j in dic.items():
input_txt=re.sub(i,j,input_txt)
>>> print(input_txt)
THE quick brown FOX jumps over the lazy DOG.
您只需更改input_txt的output2,覆盖它而不是创建新变量。您只需更改input_txt的output2,覆盖它而不是创建新变量