【发布时间】:2018-09-25 18:54:25
【问题描述】:
我有以下字符串/句子(语法不正确)
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。但它不是基于索引范围。
【问题讨论】:
-
为什么要使用索引范围? .replace() 会更简单
-
@mfitzp 索引范围是另一个代码的输出,我应该只替换那些键
标签: python arrays string python-3.x