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?
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)
You can use regular expressions:
import re
s = "aXbcXd" #example string
s = re.sub(".?X", "", s)
print(s)
#output: bd
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)
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)
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:]
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?
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)
You can use regular expressions:
import re
s = "aXbcXd" #example string
s = re.sub(".?X", "", s)
print(s)
#output: bd
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)
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)
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:]