我也有字典和字符串,我想用字典值替换子字符串。我正在使用以下代码,但未获得预期的结果。
dict1 = {'name1': 'Orange', 'name2': 'Apple', 'name3': 'Carrot', 'name4': 'Mango'}
a ="Fruit: name1 Fruit: name2 Fruit: name5 Fruit: name3 Fruit: name5"
print(a)
a_new = ''
for key in dict1.keys():
skey = a[a.find(': ') + 2 : a.find(' F')].strip()
if skey == key:
sval = dict1[key]
a_new = a[ : a.find(': ') + 1] + sval + a[a.find(' F') : ]
print(a_new)
我的代码输出
Fruit: name1 Fruit: name2 Fruit: name5 Fruit: name4 Fruit: name5
Fruit:Orange Fruit: name2 Fruit: name5 Fruit: name4 Fruit: name5
我的预期输出
Fruit: name1 Fruit: name2 Fruit: name5 Fruit: name4 Fruit: name5
Fruit: Orange Fruit: Apple Fruit: name5 Fruit: Carrot Fruit: Mango
感谢您的协助。预先感谢。
答案 0 :(得分:1)
您可以使用正则表达式查找匹配项,并使用该表达式替换字符串中的匹配词。
import re
dict1 = {'name1': 'Orange', 'name2': 'Apple', 'name3': 'Carrot', 'name4': 'Mango'}
a ="Fruit: name1 \
Fruit: name2 \
Fruit: name5 \
Fruit: name4 \
Fruit: name5 \
"
pattern = re.compile(r"\w+:\s+(\w+)")
match = re.findall(pattern, a)
for item in match:
if item in dict1.keys():
a = a.replace(item, dict1[item])
print(a)
输出:
'Fruit: Orange Fruit: Apple Fruit: name5 Fruit: Mango Fruit: name5 '
答案 1 :(得分:1)
嗯,您非常接近预期的输出。我在某处编辑了代码并获得了预期的输出,尽管您也可以使用正则表达式来完成。 find
返回与子字符串匹配的第一个匹配项,在这种情况下,您需要移动find
的搜索位置。
find(substring, start_position, end_position)
修改后的代码
dict1 = {'name1': 'Orange', 'name2': 'Apple', 'name3': 'Carrot', 'name4': 'Mango'}
a ="Fruit: name1 Fruit: name2 Fruit: name5 Fruit: name3 Fruit: name5"
offset1 = 0
offset2 = 0
print(a)
for key in dict1.keys():
skey = a[a.find(': ', offset1) + 2 : a.find(' F', offset2)].strip()
if skey in dict1.keys():
sval = dict1[key]
a = a[ : a.find(': ', offset1) + 2] +sval + '\t' + a[a.find(' F', offset2) : ]
offset1 = a.find(': ', offset1) + 1
offset2 = a.find(" F", offset2) + 1
print(a)
输出
Fruit: name1 Fruit: name2 Fruit: name5 Fruit: name3 Fruit: name5
Fruit: Orange Fruit: Apple Fruit: name5 Fruit: Mango Fruit: name5