我有以下字符串/句子(语法不正确)
s = "The user should be able to audit log to view the audit log entries."
我有一本类似的字典:
d = {'audit' : 'class1',
'audit log' : 'class2',
'audit log entries' : 'class3'}
我能够得到子字符串的索引范围,它将匹配字典中的键,我需要用它们的值替换匹配的键
final_ranges = [(49, 66), (27, 36)] #list length may vary
我想迭代索引范围并替换子字符串
我尝试了以下代码:
for i in final_ranges:
for k,v in d.items():
if s[i[0]:i[1]] == k:
print(s[0:i[0]] + v + s[i[1]:])
将输出:
The user should be able to audit log to view the class3.
The user should be able to class2 to view the audit log entries.
但我希望子串替换出现在一个句子中
The user should be able to class2 to view the class3.
我经历了这个link。但它不是基于索引范围
实际上你从来没有更新过
s
。所以,你的变化不会累积。试试这个:尽管如评论中所述,您可能应该使用replace:
如果您愿意删除
print
语句,您甚至可以将此作为列表理解:相关问题 更多 >
编程相关推荐