Python - 索引错误:字符串索引超出范围

时间:2016-02-27 21:12:23

标签: python

我试图将Adam Calhoun's experiment缩小经典小说复制到标点符号并将其呈现在海报中。

使用his code,我能够进入标点符号阶段,但是,当我尝试在海报中对其进行转换时,我得到了" IndexError:字符串索引超出范围" " symb = txt [jj + ii * symbolsPerLine]"中的错误消息线。

for ii in range(linesOfText):
    for jj in range(symbolsPerLine):
        symb = txt[jj + ii * symbolsPerLine]
        if (symb == "."):
            draw.text((trim + jj * deltaW, trim + ii * deltaH - round(font2size / 4)), symb, fill=endSentenceFill,
                      font=font2)
        elif (symb == ','):
            draw.text((trim + jj * deltaW, trim + ii * deltaH - round(font2size / 4)), symb, fill=transitionFill,
                      font=font2)
        elif (symb == '!') or (symb == '?'):
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill=endSentenceFill, font=font2)
        elif (symb == '"') or (symb == '\'') or (symb == '(') or (symb == ')') or (symb == '[') or (symb == ']'):
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill=parentheticalFill, font=font2)
        elif (symb == ';') or (symb == '-') or (symb == ':'):
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill=transitionFill, font=font2)
        else:
            draw.text((trim + jj * deltaW, trim + ii * deltaH), symb, fill="green", font=font2)

代码的问题是什么?

2 个答案:

答案 0 :(得分:0)

symb = punct[jj + ii*symbolsPerLine]

答案 1 :(得分:0)

也许这个

for ii in range(len(linesOfText)):
    for jj in range(len(symbolsPerLine)):

让我们说txt是2长但是如果ii + jj * symbolsPerLine是3它将返回索引超出范围

symb = txt[jj + ii * symbolsPerLine]