我有一个字符串,希望一次性替换字符串中的所有值

2024-05-19 23:03:14 发布

您现在位置:Python中文网/ 问答频道 /正文

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中的所有值


Tags: andoftotopicthatsentencesallare
2条回答

试试这个

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

print(str1)

一次性:

str1 = str1.replace('series', 'web').replace('sentence', 'long paragraph')

使用循环:

for to_replace, replace_with in REPLACE_STRING.items():
    str1 = str1.replace(to_replace, replace_with)

相关问题 更多 >