Languages
[Edit]
EN

Python - replace part of string from given index

0 points
Created by:
Chronal
697

In this article, we would like to show you how to replace part of string from given index in Python.

Quick solution:

text = "ABCD"
replacement = "xy"

position = 1
number_of_characters = 2

result = text[:position] + replacement + text[position + number_of_characters:]

print(result)  # AxyD

 

1. Practical example using string slicing with string concatenation

In this example, we use string slicing with string concatenation to replace CD letters (index 1-3) from the text with the replacement.

text = "ABCD"
replacement = "xy"

position = 1
number_of_characters = 2

result = text[:position] + replacement + text[position + number_of_characters:]

print(result)  # AxyD

Output:

AxyD

Explanation:

piece of codeequivalent toletter
text[:position]text[0:1]A
text[position + number_of_characters:]text[3:text.length] or text[3:4]D

2. Practical example using string slicing with join() method

In this example, we use string slicing with join() method to replace CD letters (index 1-3) from the text with the replacement.

text = "ABCD"
replacement = "xy"

position = 1
number_of_characters = 2

result = "".join((text[:position], replacement, text[position + number_of_characters:]))

print(result)  # AxyD

Output:

AxyD

Related posts

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.

Python - string (popular problems)

Python - replace part of string from given index
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