If you have a sentence in Python as String and you want to replace the first occurrence of a particular String in it, you can make use of the replace() function from the String class.
Syntax:
Let's take a look at a few examples.
Example 1: Replace String bad with good.
This example has just one occurrence of good, so we do not need to pass the maxreplace argument.
sentence = "This is a bad idea!"
new_sentence = sentence.replace("bad", "good")
print(new_sentence)
Output:
This is a good idea!
Example 2: Replace 1st $ with USD
In this example, we have two occurrences of string $, so to replace the first occurrence we need to pass the maxreplace argument as 1.
string = "This currency is in $, so you need to pay $49.99"
new_string = string.replace("$", "USD",1)
print(new_string)
Output:
This currency is in USD, so you need to pay $49.99

Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!