IndexError:字符串索引超出范围..为什么?

0 python for-loop

我想找到字符串的最后一个空格,然后在那里打破它.line_size是行必须的大小,因此它会有所不同.

if line[line_size] != ' ':
        for x in reversed(range(line_size)):
            print line[x]
            if line [x] == ' ':
            break_line = line[x]
Run Code Online (Sandbox Code Playgroud)

ava*_*sal 6

你应该使用rfind相同的

In [71]: l = "hi there what do you want"

In [72]: l.rfind(' ')
Out[72]: 20
Run Code Online (Sandbox Code Playgroud)

rfind 返回找到substring sub的字符串中的最高索引

在你的案件中的问题似乎与line_size你可以去reversed(range(len(l)))

In [76]: for x in reversed(range(len(l))):
   ....:     if l[x] == ' ':
   ....:         print x
   ....:         break
   ....:
20
Run Code Online (Sandbox Code Playgroud)