EN
Python - replace all occurrences of string
0 points
In this article, we would like to show you how to replace all occurrences of string in Python.
Quick solution:
xxxxxxxxxx
1
text = "ABC ABC ABC"
2
replacement = "X"
3
result = text.replace("C", replacement)
4
5
print(result) # ABX ABX ABX
In this example, we use String replace()
method to replace all occurrences of the "C
" letter in the text
string.
xxxxxxxxxx
1
text = "ABC ABC ABC"
2
replacement = "X"
3
result = text.replace("C", replacement)
4
5
print(result) # ABX ABX ABX
Output:
xxxxxxxxxx
1
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.
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.
xxxxxxxxxx
1
text = "ABC ABC ABC"
2
replacement = "X"
3
count = 2
4
result = text.replace("C", replacement, count)
5
6
print(result) # ABX ABX ABC
Output:
xxxxxxxxxx
1
ABX ABX ABC