首页 > 解决方案 > 我有一个字符串,想一次性替换字符串中的所有值

问题描述

str1 = "series of sentences that are organized and coherent, and are all related to a single topic. Almost every piece of writing you do that is longer than a few **sentences** should be organized into paragraphs."

REPLACE_STRING = {"series":"web" , "sentence":"long paragraph"}

输出:

web of long paragraph that are organized and coherent, and are all related to a single topic. Almost every piece of writing you do that is longer than a few **long paragraph** should be organized into paragraphs.

基本上需要一次性用字典中存在的键替换 str 中的所有值。

标签: python

解决方案


尝试这个。

for key, value in REPLACE_STRING.items():
    str1 = str1.replace(key, value)

print(str1)

推荐阅读