可以使用split()函数将字符串转换为单词列表,然后遍历该列表并将匹配的单词替换为字典中的对应单词。
代码示例:
string = "Hello World, this is a test string"
dictionary = {"Hello": "Hi", "test": "example"}
word_list = string.split()
for i in range(len(word_list)):
if word_list[i] in dictionary:
word_list[i] = dictionary[word_list[i]]
new_string = " ".join(word_list)
print(new_string)
输出:
Hi World, this is a example string