问题
I have code to append ^0
to all the constants in my code so that if you had the string "3x^2+14+2" it would become "3x^2+14^0+2^0" however I am getting a IndexError and I have no idea what I am doing wrong. This is my code:
def cleanEquation(equation):
equation = ''.join(equation.split())
for i in range(len(equation)):
if equation[i].isdigit():
if equation[i-1] != "^":
if i == len(equation)-1:
equation = equation[:i+1] + '^0'
if equation[i+1] == "+" or equation[i+1] == "-":
equation = equation[:i+1] + '^0' + equation[i+1]
cleanEquation("x+14+y+14")
Whenever I try to run this I get:
IndexError: string index out of range
This is only a snippet of the function the whole function adds 1 to the beggining of every coefficient and also adds ^1 to every variable with no coefficient and those 2 parts work fine for some reason even though they have the same format is this part of the function. I can post the full function if needed.
回答1:
for i in range(len(equation)):
uses the original length of equation
as the limit of i
. But the line:
equation = equation[:i+1] + '^0' + equation[i+1]
removes characters from equation
. When i
gets to the new length of equation
, you get an error.
You need to use a while
loop so you compare with the current length rather than the original length.
i = 0
while i < len(equation):
if equation[i].isdigit():
if equation[i-1] != "^":
if i == len(equation)-1:
equation = equation[:i+1] + '^0'
if equation[i+1] == "+" or equation[i+1] == "-":
equation = equation[:i+1] + '^0' + equation[i+1]
i += 1
You could do the whole thing with a regular expression substitution:
import re
def cleanEquation(equation):
equation = ''.join(equation.split())
equation = re.sub(r'(?<=\d\b)(?!\^)', '^0', equation)
return equation
(?<=\d\b)
is a lookbehind that matches a digit followed by a word boundary, i.e. the last digit of a numb. (?!\^)
is a negative lookahead that prevents matching if the number is already followed by ^
.
来源:https://stackoverflow.com/questions/58383273/indexerror-string-index-out-of-range-on-equation-cleaning-function