EN
Python - replace part of string from given index
0 points
In this article, we would like to show you how to replace part of string from given index in Python.
Quick solution:
xxxxxxxxxx
1
text = "ABCD"
2
replacement = "xy"
3
4
position = 1
5
number_of_characters = 2
6
7
result = text[:position] + replacement + text[position + number_of_characters:]
8
9
print(result) # AxyD
In this example, we use string slicing with string concatenation to replace CD
letters (index 1-3) from the text
with the replacement
.
xxxxxxxxxx
1
text = "ABCD"
2
replacement = "xy"
3
4
position = 1
5
number_of_characters = 2
6
7
result = text[:position] + replacement + text[position + number_of_characters:]
8
9
print(result) # AxyD
Output:
xxxxxxxxxx
1
AxyD
Explanation:
piece of code | equivalent to | letter |
---|---|---|
text[:position] | text[0:1] | A |
text[position + number_of_characters:] | text[3:text.length] or text[3:4] | D |
In this example, we use string slicing with join()
method to replace CD
letters (index 1-3) from the text
with the replacement
.
xxxxxxxxxx
1
text = "ABCD"
2
replacement = "xy"
3
4
position = 1
5
number_of_characters = 2
6
7
result = "".join((text[:position], replacement, text[position + number_of_characters:]))
8
9
print(result) # AxyD
Output:
xxxxxxxxxx
1
AxyD