Python string is out of index

Question:

I’m trying to delete ‘X’ and the char before X and here is my code

s = input()
for i in range(len(s)):
    if s[i] == 'X':
        s = s.replace("X", "")
        s = s.replace(s[i], "")

i got out of index error

    if s[i] == 'X':
IndexError: string index out of range

What’s the problem here and how to fix it?

Asked By: user12505209

||

Answers:

Solution

f= []
x = input()
for i in range(len(x)-1):
    if x[i+1]=='X' or x[i]=='X':
        continue
    else:
        f.append(x[i])

final = ''.join(f)  


Answered By: Lovleen Kaur

You can use regular expressions:

import re
s = "aXbcXd" #example string
s = re.sub(".?X", "", s)
print(s)
#output: bd
Answered By: Amin Guermazi

Solution:

s = input()
ls = len(s)
x_pos = []
for i in range(ls):
    if s[i] == 'X':
        if i != 0:
            x_pos.append(i - 1)
            x_pos.append(i)
        else:
            x_pos.append(i)
new_s = ''
for j in range(ls):
    if j not in x_pos:
        new_s += s[j]

print(new_s)
Answered By: maghsood026

In my opinion, best way to address this problem would be using regular expressions. An alternative method could be this.

Solution:

s = input()
def removeX(s):
    pos = s.find('X')
    if pos == -1:
        print(s)
        return
    elif pos == 0:
        s = s[pos+1:]
    else:
        s = s[:pos-1]+s[pos+1:]
    removeX(s)

removeX(s)
Answered By: Onion_Hash

You can use while loop

s = input()
while True:
    a = s.find('X')
    if a==-1:
        break
    if a==0:
        s = s[1:]
    else:
        s = s[:a-1]+s[a+1:]
Answered By: Sakibulislam
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.