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.


Syntax:

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

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

Reference: https://docs.python.org/2/library/string.html#string.replace


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
Example - Replace first occurrence of a String is a sentence
-

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


Author: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X

Copyright © Code2care 2023 | Privacy Policy | About Us | Contact Us | Sitemap