0

我试图将字符串的最后一个字符存储在变量中,但事先不知道字符串有多长(字符串最初是从列表中读取的)。我有:

last = record[-1]
lastInd = len(last) - 1
lastChar = last[lastInd]

但我收到以下错误:

lastChar = last[lastInd]
IndexError: string index out of range

如果我尝试:

lastChar = last[-1]

我犯了同样的错误:

lastChar = last[-1]
IndexError: string index out of range

我真的不明白这里出了什么问题?我没有得到正确的索引吗?

4

2 回答 2

5

正如inspectorG4dget 所说,获得此异常的唯一方法last[-1]是 iflast是一个空字符串。

If you want to know how to deal with it… well, it depends on what you're trying to do.

Normally, if you're trying to get the last character of a string, you expect it to be non-empty, so it should be an error if it is unexpectedly empty.

But if you want to get the last character if the string is npt empty, or an empty string if it is, there are three ways to do it, in (what I think is) declining order of pythonic-ness, at least in code written by a novice.

First, there's EAFP ("Easier to Ask for Forgiveness than Permission). Assume it'll work, try it, and deal with unexpected failure as appropriate:

try:
    lastChar = last[-1]
except IndexError:
    lastChar = ''

Then there's LBYL (Look Before You Leap). Check for unexpected cases in advance:

if last:
    lastChar = last[-1]
else:
    lastChar = ''

Finally, there's being overly clever. Write code that you won't understand three months from now without thinking it through:

lastChar = last[-1:]

This returns all characters from the last one to the end. If there are any characters, that's the same as the last one. If there are no characters, that's nothing.

Note that this only really works as intended because a string's individual elements are themselves strings. If you tried to get the last element from a list like this, you'd get a list of 1 element or an empty list, not a single possible-empty element.

于 2013-09-16T05:39:09.970 回答
3

这是因为last是一个空字符串。

看一下这个:

>>> last = 'a'
>>> last[-1]
'a'
>>> last = ''
>>> last[-1]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range

如果你想要一个空字符串作为你的最后一个字符,以防万一你有一个空字符串作为你的最后一条记录,那么你可以试试这个:

if last == '': # or `if not last`
    lastChar = ''

或者,您可以使用三元运算符:

lastChar = last[-1] if last else ''
于 2013-09-16T05:31:34.887 回答