Languages
[Edit]
EN

Python - replace all occurrences of string

0 points
Created by:
Lennox
785

In this article, we would like to show you how to replace all occurrences of string in Python.

Quick solution:

text = "ABC ABC ABC"
replacement = "X"
result = text.replace("C", replacement)

print(result)  # ABX ABX ABX

 

1. Practical example using String replace() method

In this example, we use String replace() method to replace all occurrences of the "C" letter in the text string.

text = "ABC ABC ABC"
replacement = "X"
result = text.replace("C", replacement)

print(result)  # ABX ABX ABX

Output:

ABX ABX ABX

Note:

Optionally you can add the third argument that specifies how many occurrences of the old value you want to replace. By default the replace() method replaces all occurrences.

2. Practical example using String replace() method with optional argument

In this example, we use String replace() method with the third (count) argument to replace 2 occurrences of the "C" letter in the text string.

text = "ABC ABC ABC"
replacement = "X"
count = 2
result = text.replace("C", replacement, count)

print(result)  # ABX ABX ABC

Output:

ABX ABX ABC

References

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Cross technology - replace all occurrences of string

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join