如何替换字符串中第一次出现的子字符串?

时间:2020-02-06 09:41:47

标签: python python-3.x string replace

我有一个字符串this is a simple example. this is another simple example.和一个子字符串字典,该子字符串第一次出现的子字符串应替换为

substitutions = {
    "a": "no",
    "simple": "difficult",
}

结果字符串应为this is no difficult example. this is another simple example.。我该如何实施?

1 个答案:

答案 0 :(得分:4)

str.replacecount参数一起使用

例如:

substitutions = {
    "a": "no",
    "simple": "difficult",
}

s = "this is a simple example. this is another simple example."

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