Python: Replace the First Occurrence of String in a String

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.


string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new.


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")

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)

This currency is in USD, so you need to pay $49.99
Example - Replace first occurrence of a String is a sentence

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail:

Copyright ยฉ Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap