根据索引范围将子字符串替换为字符串中的字典值

时间:2018-09-25 18:54:26

标签: python arrays string python-3.x

我有以下字符串/句子(语法上不正确)

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。但这不是基于索引范围。

1 个答案:

答案 0 :(得分:1)

您实际上从未更新过s。因此,您的更改不会产生。试试这个:

for i in final_ranges:
    key = s[i[0]:i[1]]
    if (key in d):
        s = s[:i[0]] + d[key] + s[i[1]:]
        print(s)

尽管如评论中所述,您可能应该使用replace:

for k, v in d.items():
    s = s.replace(k, v)
    print(s)

如果您愿意放弃print语句,甚至可以将其作为列表理解:

from functools import reduce
s = reduce(lambda string, kv: string.replace(kv[0], kv[1]), d.items(), s)