如何处理“字符串索引超出范围”在Python中

发布于 2025-01-18 16:51:08 字数 913 浏览 0 评论 0 原文

我正在学习一些Python,并且正在进行Python工作簿练习。现在,我被困在一个叫做strinking的字符串上。我确定您知道这意味着什么。在我的情况下,字符串必须是一个数学方程式,我的代码必须将其归为代价。 这是我的代码:

def tokenizer(x):
    x=x.replace(" ","")
    list = []
    j=0
    l=len(x)
    temp=""
    while j < len(x):
        if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
            list.append(x[j])
            j=j+1
        while x[j]>="0" and x[j]<="9":
            temp = temp + x[j]
            while j<len(x):
                j=j+1
        if temp!="":
            list.append(temp)
            temp=""
    return list

def main():
    x=input("Enter math expression: ")
    list=tokenizer(x)
    print("the tokens are: ",list)

if __name__ == '__main__':
    main()

问题是我找不到没有用完范围的解决方案。这一切都来自“ while”循环。我尝试了本书中的解决方案,该解决方案与我的书籍非常相似,但是它给出了相同的结果。在我的情况下,我如何避免使用时用尽范围并添加以对抗“ J”?

谢谢 !!!

I'm learning a bit of python and I'm doing the python workbook exercises . Right now I'm stuck on one called Tokenizing a String . I'm sure you know what that means . In my case the string must be a math equation and my code must tokenize it .
here is my code :

def tokenizer(x):
    x=x.replace(" ","")
    list = []
    j=0
    l=len(x)
    temp=""
    while j < len(x):
        if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
            list.append(x[j])
            j=j+1
        while x[j]>="0" and x[j]<="9":
            temp = temp + x[j]
            while j<len(x):
                j=j+1
        if temp!="":
            list.append(temp)
            temp=""
    return list

def main():
    x=input("Enter math expression: ")
    list=tokenizer(x)
    print("the tokens are: ",list)

if __name__ == '__main__':
    main()

So the problem is I can't find a solution where it is not running out of range . It all comes from that "while" loop . I tried the solution from the book , which was quite similar to my one , but it gives the same result . How can I avoid running out of range when I'm using while and adding to counter "j" in my case?

Thanks !!!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

不再让梦枯萎 2025-01-25 16:51:08

问题是您在此块中添加1至 j

while j < len(x):
    if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
        list.append(x[j])
        j=j+1
    while x[j]>="0" and x[j]<="9":
        temp = temp + x[j]
        while j<len(x):
            j=j+1
    if temp!="":
        list.append(temp)
        temp=""

让我们说 j = len(x)-1 -1 和if语句评估为 true 。这将执行 J = J+1 语句。
现在,当它输入时loop 时,它会检查 x [j]&gt; =“ 0” x [j] = x [j]&gt; =“ 0”
> x [len(x)]
。由于我们知道索引从零开始,因此对于

a = "abcd"

len(a)= 4 a [4] 不存在的数组(最后一个元素是第三个) indexError

带有更正的代码:

def tokenizer(x):
    x=x.replace(" ","")
    list = []
    j=0
    l=len(x)
    temp=""
    while j < len(x):
        if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
            list.append(x[j])
            print(x[j])
            print(list)
            j=j+1
        else: # Error 1: You code needs to execute this only if
              # the above condition fails
            j = j
            while j<len(x) and x[j].isnumeric(): # 2: You need to check both
                                                 # if the current character 
                                                 # is an integer and if 
                                                 # the index is out of range
                
                temp = temp + x[j]
                # while j<len(x)-1: No need for this statement
                j=j+1
            if temp!="":
                list.append(temp)
                temp=""
            
    return list

def main():
    x=input("Enter math expression: ")
    list=tokenizer(x)
    print("the tokens are: ",list)

if __name__ == '__main__':
    main()

The problem is you are adding 1 to j in this block:

while j < len(x):
    if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
        list.append(x[j])
        j=j+1
    while x[j]>="0" and x[j]<="9":
        temp = temp + x[j]
        while j<len(x):
            j=j+1
    if temp!="":
        list.append(temp)
        temp=""

Let's say j = len(x)-1 and the if statement evaluates to be True. This will execute the j=j+1 statement.
Now when it enters the while loop, it checks whether x[j]>="0" but x[j] = x[len(x)]. Since we know that indexing starts at zero, for an array like

a = "abcd"

len(a) = 4 but a[4] does not exist(last element is 3rd one) causing an IndexError.

Code with corrections:

def tokenizer(x):
    x=x.replace(" ","")
    list = []
    j=0
    l=len(x)
    temp=""
    while j < len(x):
        if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
            list.append(x[j])
            print(x[j])
            print(list)
            j=j+1
        else: # Error 1: You code needs to execute this only if
              # the above condition fails
            j = j
            while j<len(x) and x[j].isnumeric(): # 2: You need to check both
                                                 # if the current character 
                                                 # is an integer and if 
                                                 # the index is out of range
                
                temp = temp + x[j]
                # while j<len(x)-1: No need for this statement
                j=j+1
            if temp!="":
                list.append(temp)
                temp=""
            
    return list

def main():
    x=input("Enter math expression: ")
    list=tokenizer(x)
    print("the tokens are: ",list)

if __name__ == '__main__':
    main()
淡笑忘祈一世凡恋 2025-01-25 16:51:08

我不知道为什么会起作用:

def tokenizer(x):
    x=x.replace(" ","")
    list = []
    j=0
    l=len(x)
    temp=""
    while j < len(x):
        if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
            list.append(x[j])
            j=j+1
        while j<len(x) and x[j].isnumeric():
                temp=temp+x[j]
                j=j+1
        if temp!="":
            list.append(temp)
            temp=""

    return list

def main():
    x=input("Enter math expression: ")
    list=tokenizer(x)
    print("the tokens are: ",list)

if __name__ == '__main__':
    main()

我更改了“ x [j]&gt; =“ 0”和x [j]&lt; =“ 9”“使用.isnumeric()的语句,并且由于某些奇怪的原因,它现在有效。对我来说,这两个条件都是相同的。谁能解释为什么有效?我真的很想学习如何克服以后的案件而不会失去理智!!!

谢谢

I have no idea why but this works :

def tokenizer(x):
    x=x.replace(" ","")
    list = []
    j=0
    l=len(x)
    temp=""
    while j < len(x):
        if x[j] == "*" or x[j] == "/" or x[j] == "+" or x[j] == "-" or x[j] == "^" or x[j] == "(" or x[j] == ")":
            list.append(x[j])
            j=j+1
        while j<len(x) and x[j].isnumeric():
                temp=temp+x[j]
                j=j+1
        if temp!="":
            list.append(temp)
            temp=""

    return list

def main():
    x=input("Enter math expression: ")
    list=tokenizer(x)
    print("the tokens are: ",list)

if __name__ == '__main__':
    main()

I change the " x[j]>="0" and x[j]<="9"" statement with .isnumeric() and for some weird reason it now works . For me both conditions are identical . Can anyone explain why this works ? I really want to learn how to overcome cases like that in future without loosing my sanity !!!

Thanks

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文