Note

Python - replace() - Replace parts of a string


Replace parts of a string with other string - Python function replace() with examples

string.replace(old: str, new: str, count: int) is a built-in function used to replace occurrences of a specific substring in a string with another substring. It also accepts the optional argument count that needs to be an integer. If provided, it will replace only count first occurrences of a provided substring. Remember that replace() is case-sensitive!

Arguments:

  • old: The substring to be replaced.

  • new: The substring to replace old with.

  • count (optional): The maximum number of occurrences to replace. Defaults to replacing all occurrences.

Take a look at the examples below:


Basic String Replacement

original_string = "Hello, World!"
modified_string = original_string.replace("Hello", "Welcome")

print(modified_string)  # Welcome, World!

Output:

Welcome, World!

Removing Substrings

Please note that function replace() needs to be called on your string and also assigned to a new variable. It isn't possible to replace a string in-place (strings are immutable).

It can be also used to remove unwanted elements in your string. In the example below we will get rid of the spaces:

original_string = "This is an example sentence."
modified_string = original_string.replace(" ", "")

print(modified_string)  # Thisisanexamplesentence.

Output:

Thisisanexamplesentence.

Replacing a Limited Number of Occurrences

You can also provide an optional, third argument that will tell the function replace() how many occurrences you want to replace:

original_string = "@ @ @ @ @"
modified_string = original_string.replace("@", "$", 2)

print(modified_string)  # $ $ @ @ @

Output:

$ $ @ @ @

Since in this example we provided 2 as an optional argument, only the first two signs @ were replaced with $ signs.

Key Points to Remember about the replace() Function


  • Strings are immutable: so replace() does not modify the original string. It returns a new string with the changes applied.

  • Removing Substrings: Replace unwanted substrings with an empty string ("").

  • Case Sensitivity: replace() is case-sensitive.

  • Optional Count: Use the count argument to limit the number of replacements.

I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!

Thank You Image


You might also be interested in: