我有一个字符串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.
。我该如何实施?
答案 0 :(得分:4)
将str.replace
与count
参数一起使用
例如:
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)