Python 索引器错误:检查回文时字符串索引超出范围

Python 索引器错误:检查回文时字符串索引超出范围,python,Python,检查回文 我是python新手。但是我做了调试。但是找不到错误 import string def is_palindrome(str_1, lowest_index, highest_index): punct = set(string.punctuation) print(punct) #remove punctuations no_punct = "" for char in str_1: if char not in punct:

检查回文

我是python新手。但是我做了调试。但是找不到错误

import string

def is_palindrome(str_1, lowest_index, highest_index):
    punct = set(string.punctuation)
    print(punct)
    #remove punctuations
    no_punct = ""
    for char in str_1:
        if char not in punct:
            no_punct = no_punct + char
    print(no_punct)
    # rmv_whtspc = no_punct.rstrip()
    rmv_whtspc = no_punct.replace(' ','')
    print(rmv_whtspc)
    str_2 = rmv_whtspc.lower()
    print(str_2)
    if lowest_index > highest_index:
        return True
    else:
        if str_2[lowest_index] == str_2[highest_index]:
            return is_palindrome(str_2, lowest_index+1, highest_index-1)
        else:
            return False
调用函数:

str_1 = "Madama I am adam"
lowest_index = 0
highest_index = len(str_1)-1
print(is_palindrome(str_1, lowest_index, highest_index))
输出:

{'{', '<', '_', '$', '"', ',', '&', '\\', ']', '`', '%', "'", '#', '*', '+', '>', '/', '?', '=', '^', ')', '[', '(',
'~', '!', '@', '|', '}', ':', '.', ';', '-'}
Madama I am adam
MadamaIamadam
madamaiamadam

Traceback (most recent call last):
  File "recursion_5_2problem.py", line 27, in <module>
    print(is_palindrome(str_1, lowest_index, highest_index))
  File "recursion_5_2problem.py", line 19, in is_palindrome
    if str_2[lowest_index] == str_2[highest_index]:
IndexError: string index out of range
{'{'、'''/'、'?'、'='、'^'、')、'['、'(',,
'~', '!', '@', '|', '}', ':', '.', ';', '-'}
妈妈,我是亚当
马达米亚亚当
马达米亚亚当
回溯(最近一次呼叫最后一次):
文件“recursion_5_2problem.py”,第27行,在
打印(是回文(str_1,最低索引,最高索引))
文件“recursion_5_2problem.py”,第19行,is_回文
如果str_2[最低索引]==str_2[最高索引]:
索引器错误:字符串索引超出范围

在清理字符串(删除标点符号和空格)之前,您将获得最低和最高索引。因此,您正在尝试访问字符串中可能超出边界的字符。 我建议在使用回文函数之前清理字符串,然后获取函数本身的最低和最高索引(也就是在删除所有标点和空格之后)

只是伪代码,但我相信你明白了


希望有帮助!:)

中很好地描述了你犯的错误

这里有一个建议,可以让这一切变得更简单:

对于清理,您可以使用和
str.translate
;然后只需将字符串的前半部分与后半部分进行比较(相反):

您可以将其用作:

strg = "Madama I am adam"
strg = normalize(strg)     # madamaiamadam
print(ispalindrome(strg))  # True

事实上,我试图检查Madam I'm adam的回文。因此,我在代码中加入了标点符号方法,因为代码以字符形式计数(')。后来,我将文本编辑为Madama I am adam。我错过了代码最后的句号。
from string import punctuation, whitespace

repl_table = str.maketrans("", "", punctuation + whitespace)

def normalize(strg):
    # remove all punctuation and whitespace and lowercase strg
    return strg.translate(repl_table).lower()


def ispalindrome(strg):
    n2 = len(strg) // 2
    return strg[:n2] == "".join(reversed(strg))[0:n2]
strg = "Madama I am adam"
strg = normalize(strg)     # madamaiamadam
print(ispalindrome(strg))  # True