Python索引器:字符串超出范围

Python索引器:字符串超出范围,python,Python,嗨,我刚开始学习Python,遇到了一个问题。以下是我的部分职能: for i in range(0,len(list(string))): if string[i] in punctuation: if i == len(list(string))-1: new_string += string[i] if string[i+1] or string[i-1] == ' ': continue

嗨,我刚开始学习Python,遇到了一个问题。以下是我的部分职能:

for i in range(0,len(list(string))):
    if string[i] in punctuation:
        if i == len(list(string))-1:
             new_string += string[i]
        if string[i+1] or string[i-1] == ' ':
            continue
        elif string[i+1] or string[i-1] in punctuation:
            continue
        else:
            new_string += string[i]

    elif string[i] in numbers:
        new_string += ' '

    else:
        new_string += string[i]
此段将获取一个字符串并返回一个新的_字符串,该字符串将删除所有标点符号,但不删除字母之间的标点符号,例如撇号(如jacob's)或hypens(如long-Sethed)。然而,我得到一个错误,说:

if doc[i+1] or doc[i-1] == ' ':
IndexError: string index out of range
我认为代码中的第3行可以防止错误的发生,但我看不出哪里出了问题。也就是说,我的代码效率太低了吗


谢谢大家!

为了避免索引器,有时可能更容易调整范围,例如:

from string import punctuation as punct

def remove_punctuation(old_string):
    """Remove punctuation from "string" if not between 2 letters."""
    new_string =''
    s = ' ' + old_string + ' '
    for i in range(1, len(s) - 1):
        if s[i] in punct and (not s[i - 1].isalpha() or not s[i + 1].isalpha()):
            continue
        else:
            new_string += s[i]
    return new_string

如果
不是
elif
。投票以打字错误结束。@RahulBharadwaj:你还有一些问题被错误地归咎于
elif
的消失。它没有消失。@RahulBharadwaj
如果字符串[i+1]或字符串[i-1]='':
必须是
如果字符串[i+1]=''或字符串[i-1]='':
@user2357112感谢您的更正。我正在用“abc def”这样的字符串测试代码,其中连字符应该出现在新的_字符串中,但是它返回“abcdef”,这是为什么?