Replace character in String by index in Python
📋 Table Of Content
In this article, we will see how we can replace a character at a certain index in a string in python with some examples.
To replace any character at a specific position we have to use the index of the particular character and then replace the old character with the new one.
Here, we will discuss two ways to replace any character in a string at a specific index using :
- The string slicing method
- The list() and join() method.
Replace a character in a string using slice() in Python
The string slicing method helps to return a range of characters from a string by slicing it.
The method takes in a start index, a stop index, and a step count. All the parameters are separated by a colon.
Let's see an example to extract the characters from position 2 to position 6:
str = "HelloCoder" print(str[2:6]) #output: lloC
If the start index is not defined
str[:6], then it's considered to be index 0.
If the end index is not defined
str[2:], then it extracts all the characters till the last index.
So we can use the string slicing method and replace a character like the example below.
string = 'HeLLO' index = 1 character = 'E' def replaceByIndex(strg, index, new_chr): strg = strg[:index] + new_chr + strg[index+1:] return strg print(replaceByIndex(string,index,character))
Here, in this example, we have created a function replaceByIndex, which takes in three parameters: the original string(str), the index, and the new character(new_chr).
str[:index] extract the character "H" from the string.
new_chr is the character we will replace the old character with.
str[index+1:0] slice the character from index 1 up to the last index, which returns us the last three characters i.e ("LLO")
In the end, we concatenate all three parts together with
+ and return the new string.
Change character at a specific index using list in Python
We can also use the
list() and the
join() methods to change characters at a specific position.
To replace it:
- First, we have to convert the string to a list.
- Using the index of the character we have to replace it with the new one.
- Use the join() method to join the list to a string.
Let's see an example of it
string = 'Aereplane' index = 3 new_chr = 'o' chng_str = list(string) chng_str[index] = new_chr string = "".join(chng_str) print(string) #Aeroplane
Conclusion: In this short post, we have learned about how we can change any character in a string using its index with the help of python.