Python 3.6: Text Eraser Program

All I want is to find and “erase” the given characters from a string. Why is it giving me an error?

data = "<html><head>Srujan</head></html>"
tof = "Srujan"

toflen = len(tof)
posc = data.find(tof)

adata = list(data)

while posc + toflen > posc:
    adata[posc] = " "
    posc += 1

ndata = "".join(adata)
print (ndata)

The Error:

Traceback (most recent call last):
  File "E:/Scripts/sandbox.py", line 10, in <module>
    adata[posc] = ''
IndexError: list assignment index out of range
>>> 

Thank you for your help!

At some point posc becomes 32 which is the same value as adata’s length,. Arrays are zero-indexed, so there is no 32nd index , which results in this “index out of range” error.

1 Like

Thank you so much for your reply; I understood what you are trying to say with zero indexing in arrays. I modified the code but I am getting back the same string just as the input without any changes that I want. Here:

data = "<html><head>Srujan</head></html>"
tof = "Srujan"

#length determinants
toflen = len(tof)
radtlen = len(data)

#position
posc = data.find(tof)

#spliting the data into an array of individual characters including spaces.
adata = list(data)

#brain-init-vars
posx = toflen + posc
endx = radtlen - posx

#<brain>
while posx < endx:
    adata[posc] = " "
    posc += 1
#</brain>

#create new data
ndata = "".join(adata)

#output
print (ndata)

The Output:

<html><head>Srujan</head></html>

Thanks!

data = "<html><head>Srujan</head></html>"
tof = "Srujan"

#length determinants
toflen = len(tof)
radtlen = len(data)

#position
posc = data.find(tof)

#spliting the data into an array of individual characters including spaces.
adata = list(data)

#brain-init-vars
endx = posc + toflen - 1

#<brain>
while posc <= endx:
    adata[posc] = ""
    posc += 1
#</brain>

#create new data
ndata = "".join(adata)

#output
print (ndata)
1 Like