IndexError:公式清洁函数的字符串索引超出范围 [英] IndexError: string index out of range on equation cleaning function
问题描述
我有代码将 ^ 0
附加到代码中的所有常量,这样,如果您使用字符串"3x ^ 2 + 14 + 2",它将变成"3x ^ 2 + 14 ^0 + 2 ^ 0,但是我收到了IndexError,我不知道自己在做什么错.这是我的代码:
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
这只是函数的一小段,整个函数将每个系数的开头加1,并将每个没有系数的变量加^ 1,并且这两个部分出于某种原因即使它们的格式相同也可以正常工作这部分功能.如果需要,我可以发布全部功能.
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.
推荐答案
for i in range(len(equation)):
使用 equation
的原始长度作为 i
的限制.但是这行:
uses the original length of equation
as the limit of i
. But the line:
equation = equation[:i+1] + '^0' + equation[i+1]
从等式
中删除字符.当 i
达到新的 equation
长度时,您会得到一个错误.
removes characters from equation
. When i
gets to the new length of equation
, you get an error.
您需要使用 while
循环,以便与当前长度而不是原始长度进行比较.
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)
是一个向后匹配的数字,与一个数字和一个单词边界(即一个数字的最后一个数字)匹配.(?!\ ^)
是一个否定的超前查询,如果该数字后面已经跟有 ^
,则会阻止匹配.
(?<=\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 ^
.
这篇关于IndexError:公式清洁函数的字符串索引超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!