PadhaiTime Logo
Padhai Time

String Replacement in Python

When we have a string variable and we need to replace any character from it, then we simply try to replace it by assigning a new value at a specific index.

For. e.g.

str_var = "Hello Padha Time"

In this example, “i” is missing from word “Padhai”, hence we would try to do the hack as follows:

k = 11
str_var[k] = "i"

This hack we might have already done in C and C++, but it is not an allowed operation in Python. Because Strings are Immutable in Python meaning they can’t be altered/changed once created.

Therefore the above statement would throw the error as:

TypeError                                 Traceback (most recent call last)
<ipython-input-17-6ea90ea799d0> in <module>
      1 k = 11
----> 2 str_var[k] = "i"

TypeError: 'str' object does not support item assignment

 

Now the question comes to mind: How to achieve this in Python then?

Well, we need to perform Slicing and Concatenation operations to achieve this.

str_var = "Hello Padha Time"
K = 11     # index is where we need to add “i” in the string

 

str_var[:11] means we need all the elements from the starting till the 11th character from the string.

Note: Indexing in python starts from 0. Hence str_var[:11] will take all the elements from 0 to index no. 10.

str_var[11:] means we need all the elements from 12th character (index no. 11) till the end

undefined

Python code:

str_var = "Hello Padha Time"
k = 11
str_var = str_var[ : k] + "i" + str_var[k : ]      
print(str_var)

 

First slicing of string is done where we have taken First half separately and second half separately and then through concatenation operation (+) we have simply inserted the missing character “i” in between them.

Bengaluru, India
contact.padhaitime@gmail.com
  • We collect cookies and may share with 3rd party vendors for analytics, advertising and to enhance your experience. You can read more about our cookie policy by clicking on the 'Learn More' Button. By Clicking 'Accept', you agree to use our cookie technology.
    Our Privacy policy can be found by clicking here