thinwybk
thinwybk

Reputation: 4743

How can I replace the first occurence of a sub-string in a string?

I have a string this is a simple example. this is another simple example. and a dict of sub-strings and the sub-strings the first occurence of the sub-string shall be replaced with

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

The resulting string shall be this is no difficult example. this is another simple example.. How can I implement this?

Upvotes: 1

Views: 53

Answers (1)

Rakesh
Rakesh

Reputation: 82795

Use str.replace with count param

Ex:

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) 

Upvotes: 4

Related Questions